1\input texinfo @c -*-texinfo-*- 2@c %**start of header 3 4@c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo 5@c o 6@c GNAT DOCUMENTATION o 7@c o 8@c G N A T _ U G N o 9@c o 10@c Copyright (C) 1992-2013, Free Software Foundation, Inc. o 11@c o 12@c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo 13 14@setfilename gnat_ugn.info 15 16@copying 17Copyright @copyright{} 1995-2009 Free Software Foundation, 18Inc. 19 20Permission is granted to copy, distribute and/or modify this document 21under the terms of the GNU Free Documentation License, Version 1.3 or 22any later version published by the Free Software Foundation; with no 23Invariant Sections, with no Front-Cover Texts and with no Back-Cover 24Texts. A copy of the license is included in the section entitled 25``GNU Free Documentation License''. 26@end copying 27 28@c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo 29@c 30@c GNAT_UGN Style Guide 31@c 32@c 1. Always put a @noindent on the line before the first paragraph 33@c after any of these commands: 34@c 35@c @chapter 36@c @section 37@c @subsection 38@c @subsubsection 39@c @subsubsubsection 40@c 41@c @end smallexample 42@c @end itemize 43@c @end enumerate 44@c 45@c 2. DO NOT use @example. Use @smallexample instead. 46@c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample 47@c context. These can interfere with the readability of the texi 48@c source file. Instead, use one of the following annotated 49@c @smallexample commands, and preprocess the texi file with the 50@c ada2texi tool (which generates appropriate highlighting): 51@c @smallexample @c ada 52@c @smallexample @c adanocomment 53@c @smallexample @c projectfile 54@c b) The "@c ada" markup will result in boldface for reserved words 55@c and italics for comments 56@c c) The "@c adanocomment" markup will result only in boldface for 57@c reserved words (comments are left alone) 58@c d) The "@c projectfile" markup is like "@c ada" except that the set 59@c of reserved words include the new reserved words for project files 60@c 61@c 3. Each @chapter, @section, @subsection, @subsubsection, etc. 62@c command must be preceded by two empty lines 63@c 64@c 4. The @item command should be on a line of its own if it is in an 65@c @itemize or @enumerate command. 66@c 67@c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali" 68@c or "ali". 69@c 70@c 6. DO NOT put trailing spaces at the end of a line. Such spaces will 71@c cause the document build to fail. 72@c 73@c 7. DO NOT use @cartouche for examples that are longer than around 10 lines. 74@c This command inhibits page breaks, so long examples in a @cartouche can 75@c lead to large, ugly patches of empty space on a page. 76@c 77@c NOTE: This file should be submitted to xgnatugn with either the vms flag 78@c or the unw flag set. The unw flag covers topics for both Unix and 79@c Windows. 80@c 81@c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo 82 83@set NOW January 2007 84@c This flag is used where the text refers to conditions that exist when the 85@c text was entered into the document but which may change over time. 86@c Update the setting for the flag, and (if necessary) the text surrounding, 87@c the references to the flag, on future doc revisions: 88@c search for @value{NOW}. 89 90@set FSFEDITION 91@set EDITION GNAT 92@set DEFAULTLANGUAGEVERSION Ada 2005 93@set NONDEFAULTLANGUAGEVERSION Ada 95 94 95@ifset unw 96@set PLATFORM 97@set TITLESUFFIX 98@end ifset 99 100@ifset vms 101@set PLATFORM OpenVMS 102@set TITLESUFFIX for OpenVMS 103@end ifset 104 105@c @ovar(ARG) 106@c ---------- 107@c The ARG is an optional argument. To be used for macro arguments in 108@c their documentation (@defmac). 109@macro ovar{varname} 110@r{[}@var{\varname\}@r{]}@c 111@end macro 112@c Status as of November 2009: 113@c Unfortunately texi2pdf and texi2html treat the trailing "@c" 114@c differently, and faulty output is produced by one or the other 115@c depending on whether the "@c" is present or absent. 116@c As a result, the @ovar macro is not used, and all invocations 117@c of the @ovar macro have been expanded inline. 118 119 120@settitle @value{EDITION} User's Guide @value{TITLESUFFIX} 121@dircategory GNU Ada tools 122@direntry 123* @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM} 124@end direntry 125 126@include gcc-common.texi 127 128@setchapternewpage odd 129@syncodeindex fn cp 130@c %**end of header 131 132@titlepage 133@title @value{EDITION} User's Guide 134@ifset vms 135@sp 1 136@flushright 137@titlefont{@i{@value{PLATFORM}}} 138@end flushright 139@end ifset 140 141@sp 2 142 143@subtitle GNAT, The GNU Ada Compiler 144@versionsubtitle 145@author AdaCore 146 147@page 148@vskip 0pt plus 1filll 149 150@insertcopying 151 152@end titlepage 153 154@ifnottex 155@node Top, About This Guide, (dir), (dir) 156@top @value{EDITION} User's Guide 157 158@noindent 159@value{EDITION} User's Guide @value{PLATFORM} 160 161@noindent 162GNAT, The GNU Ada Compiler@* 163GCC version @value{version-GCC}@* 164 165@noindent 166AdaCore@* 167 168@menu 169* About This Guide:: 170* Getting Started with GNAT:: 171* The GNAT Compilation Model:: 172* Compiling Using gcc:: 173* Binding Using gnatbind:: 174* Linking Using gnatlink:: 175* The GNAT Make Program gnatmake:: 176* Improving Performance:: 177* Renaming Files Using gnatchop:: 178* Configuration Pragmas:: 179* Handling Arbitrary File Naming Conventions Using gnatname:: 180* GNAT Project Manager:: 181* Tools Supporting Project Files:: 182* The Cross-Referencing Tools gnatxref and gnatfind:: 183* The GNAT Pretty-Printer gnatpp:: 184* The GNAT Metric Tool gnatmetric:: 185* File Name Krunching Using gnatkr:: 186* Preprocessing Using gnatprep:: 187* The GNAT Library Browser gnatls:: 188* Cleaning Up Using gnatclean:: 189@ifclear vms 190* GNAT and Libraries:: 191* Using the GNU make Utility:: 192@end ifclear 193* Memory Management Issues:: 194* Stack Related Facilities:: 195* Verifying Properties Using gnatcheck:: 196* Creating Sample Bodies Using gnatstub:: 197* Creating Unit Tests Using gnattest:: 198* Performing Dimensionality Analysis in GNAT:: 199* Generating Ada Bindings for C and C++ headers:: 200* Other Utility Programs:: 201* Running and Debugging Ada Programs:: 202@ifclear vms 203* Code Coverage and Profiling:: 204@end ifclear 205@ifset vms 206* Compatibility with HP Ada:: 207@end ifset 208* Platform-Specific Information for the Run-Time Libraries:: 209* Example of Binder Output File:: 210* Elaboration Order Handling in GNAT:: 211* Overflow Check Handling in GNAT:: 212* Conditional Compilation:: 213* Inline Assembler:: 214* Compatibility and Porting Guide:: 215@ifset unw 216* Microsoft Windows Topics:: 217* Mac OS Topics:: 218@end ifset 219* GNU Free Documentation License:: 220* Index:: 221 222 --- The Detailed Node Listing --- 223 224About This Guide 225 226* What This Guide Contains:: 227* What You Should Know before Reading This Guide:: 228* Related Information:: 229* Conventions:: 230 231Getting Started with GNAT 232 233* Running GNAT:: 234* Running a Simple Ada Program:: 235* Running a Program with Multiple Units:: 236* Using the gnatmake Utility:: 237@ifset vms 238* Editing with Emacs:: 239@end ifset 240@ifclear vms 241* Introduction to GPS:: 242@end ifclear 243 244The GNAT Compilation Model 245 246* Source Representation:: 247* Foreign Language Representation:: 248* File Naming Rules:: 249* Using Other File Names:: 250* Alternative File Naming Schemes:: 251* Generating Object Files:: 252* Source Dependencies:: 253* The Ada Library Information Files:: 254* Binding an Ada Program:: 255* Mixed Language Programming:: 256@ifclear vms 257* Building Mixed Ada & C++ Programs:: 258* Comparison between GNAT and C/C++ Compilation Models:: 259@end ifclear 260* Comparison between GNAT and Conventional Ada Library Models:: 261@ifset vms 262* Placement of temporary files:: 263@end ifset 264 265Foreign Language Representation 266 267* Latin-1:: 268* Other 8-Bit Codes:: 269* Wide Character Encodings:: 270 271Compiling Ada Programs With gcc 272 273* Compiling Programs:: 274* Switches for gcc:: 275* Search Paths and the Run-Time Library (RTL):: 276* Order of Compilation Issues:: 277* Examples:: 278 279Switches for gcc 280 281* Output and Error Message Control:: 282* Warning Message Control:: 283* Debugging and Assertion Control:: 284* Validity Checking:: 285* Style Checking:: 286* Run-Time Checks:: 287* Using gcc for Syntax Checking:: 288* Using gcc for Semantic Checking:: 289* Compiling Different Versions of Ada:: 290* Character Set Control:: 291* File Naming Control:: 292* Subprogram Inlining Control:: 293* Auxiliary Output Control:: 294* Debugging Control:: 295* Exception Handling Control:: 296* Units to Sources Mapping Files:: 297* Integrated Preprocessing:: 298@ifset vms 299* Return Codes:: 300@end ifset 301 302Binding Ada Programs With gnatbind 303 304* Running gnatbind:: 305* Switches for gnatbind:: 306* Command-Line Access:: 307* Search Paths for gnatbind:: 308* Examples of gnatbind Usage:: 309 310Switches for gnatbind 311 312* Consistency-Checking Modes:: 313* Binder Error Message Control:: 314* Elaboration Control:: 315* Output Control:: 316* Binding with Non-Ada Main Programs:: 317* Binding Programs with No Main Subprogram:: 318 319Linking Using gnatlink 320 321* Running gnatlink:: 322* Switches for gnatlink:: 323 324The GNAT Make Program gnatmake 325 326* Running gnatmake:: 327* Switches for gnatmake:: 328* Mode Switches for gnatmake:: 329* Notes on the Command Line:: 330* How gnatmake Works:: 331* Examples of gnatmake Usage:: 332 333Improving Performance 334* Performance Considerations:: 335* Text_IO Suggestions:: 336* Reducing Size of Ada Executables with gnatelim:: 337* Reducing Size of Executables with unused subprogram/data elimination:: 338 339Performance Considerations 340* Controlling Run-Time Checks:: 341* Use of Restrictions:: 342* Optimization Levels:: 343* Debugging Optimized Code:: 344* Inlining of Subprograms:: 345* Vectorization of loops:: 346* Other Optimization Switches:: 347* Optimization and Strict Aliasing:: 348@ifset vms 349* Coverage Analysis:: 350@end ifset 351 352Reducing Size of Ada Executables with gnatelim 353* About gnatelim:: 354* Running gnatelim:: 355* Processing Precompiled Libraries:: 356* Correcting the List of Eliminate Pragmas:: 357* Making Your Executables Smaller:: 358* Summary of the gnatelim Usage Cycle:: 359 360Reducing Size of Executables with unused subprogram/data elimination 361* About unused subprogram/data elimination:: 362* Compilation options:: 363 364Renaming Files Using gnatchop 365 366* Handling Files with Multiple Units:: 367* Operating gnatchop in Compilation Mode:: 368* Command Line for gnatchop:: 369* Switches for gnatchop:: 370* Examples of gnatchop Usage:: 371 372Configuration Pragmas 373 374* Handling of Configuration Pragmas:: 375* The Configuration Pragmas Files:: 376 377Handling Arbitrary File Naming Conventions Using gnatname 378 379* Arbitrary File Naming Conventions:: 380* Running gnatname:: 381* Switches for gnatname:: 382* Examples of gnatname Usage:: 383 384The Cross-Referencing Tools gnatxref and gnatfind 385 386* Switches for gnatxref:: 387* Switches for gnatfind:: 388* Project Files for gnatxref and gnatfind:: 389* Regular Expressions in gnatfind and gnatxref:: 390* Examples of gnatxref Usage:: 391* Examples of gnatfind Usage:: 392 393The GNAT Pretty-Printer gnatpp 394 395* Switches for gnatpp:: 396* Formatting Rules:: 397 398The GNAT Metrics Tool gnatmetric 399 400* Switches for gnatmetric:: 401 402File Name Krunching Using gnatkr 403 404* About gnatkr:: 405* Using gnatkr:: 406* Krunching Method:: 407* Examples of gnatkr Usage:: 408 409Preprocessing Using gnatprep 410* Preprocessing Symbols:: 411* Using gnatprep:: 412* Switches for gnatprep:: 413* Form of Definitions File:: 414* Form of Input Text for gnatprep:: 415 416The GNAT Library Browser gnatls 417 418* Running gnatls:: 419* Switches for gnatls:: 420* Examples of gnatls Usage:: 421 422Cleaning Up Using gnatclean 423 424* Running gnatclean:: 425* Switches for gnatclean:: 426@c * Examples of gnatclean Usage:: 427 428@ifclear vms 429 430GNAT and Libraries 431 432* Introduction to Libraries in GNAT:: 433* General Ada Libraries:: 434* Stand-alone Ada Libraries:: 435* Rebuilding the GNAT Run-Time Library:: 436 437Using the GNU make Utility 438 439* Using gnatmake in a Makefile:: 440* Automatically Creating a List of Directories:: 441* Generating the Command Line Switches:: 442* Overcoming Command Line Length Limits:: 443@end ifclear 444 445Memory Management Issues 446 447* Some Useful Memory Pools:: 448* The GNAT Debug Pool Facility:: 449@ifclear vms 450* The gnatmem Tool:: 451@end ifclear 452 453Stack Related Facilities 454 455* Stack Overflow Checking:: 456* Static Stack Usage Analysis:: 457* Dynamic Stack Usage Analysis:: 458 459Some Useful Memory Pools 460 461The GNAT Debug Pool Facility 462 463@ifclear vms 464The gnatmem Tool 465 466* Running gnatmem:: 467* Switches for gnatmem:: 468* Example of gnatmem Usage:: 469@end ifclear 470 471Verifying Properties Using gnatcheck 472 473Sample Bodies Using gnatstub 474 475* Running gnatstub:: 476* Switches for gnatstub:: 477 478Creating Unit Tests Using gnattest 479 480* Running gnattest:: 481* Switches for gnattest:: 482* Project Attributes for gnattest:: 483* Simple Example:: 484* Setting Up and Tearing Down the Testing Environment:: 485* Regenerating Tests:: 486* Default Test Behavior:: 487* Testing Primitive Operations of Tagged Types:: 488* Testing Inheritance:: 489* Tagged Types Substitutability Testing:: 490* Testing with Contracts:: 491* Additional Tests:: 492@ifclear vms 493* Support for other platforms/run-times:: 494@end ifclear 495* Current Limitations:: 496 497Other Utility Programs 498 499* Using Other Utility Programs with GNAT:: 500* The External Symbol Naming Scheme of GNAT:: 501* Converting Ada Files to html with gnathtml:: 502 503@ifclear vms 504Code Coverage and Profiling 505 506* Code Coverage of Ada Programs using gcov:: 507* Profiling an Ada Program using gprof:: 508@end ifclear 509 510Running and Debugging Ada Programs 511 512* The GNAT Debugger GDB:: 513* Running GDB:: 514* Introduction to GDB Commands:: 515* Using Ada Expressions:: 516* Calling User-Defined Subprograms:: 517* Using the Next Command in a Function:: 518* Ada Exceptions:: 519* Ada Tasks:: 520* Debugging Generic Units:: 521* Remote Debugging using gdbserver:: 522* GNAT Abnormal Termination or Failure to Terminate:: 523* Naming Conventions for GNAT Source Files:: 524* Getting Internal Debugging Information:: 525* Stack Traceback:: 526 527@ifset vms 528* LSE:: 529@end ifset 530 531@ifset vms 532Compatibility with HP Ada 533 534* Ada Language Compatibility:: 535* Differences in the Definition of Package System:: 536* Language-Related Features:: 537* The Package STANDARD:: 538* The Package SYSTEM:: 539* Tasking and Task-Related Features:: 540* Pragmas and Pragma-Related Features:: 541* Library of Predefined Units:: 542* Bindings:: 543* Main Program Definition:: 544* Implementation-Defined Attributes:: 545* Compiler and Run-Time Interfacing:: 546* Program Compilation and Library Management:: 547* Input-Output:: 548* Implementation Limits:: 549* Tools and Utilities:: 550 551Language-Related Features 552 553* Integer Types and Representations:: 554* Floating-Point Types and Representations:: 555* Pragmas Float_Representation and Long_Float:: 556* Fixed-Point Types and Representations:: 557* Record and Array Component Alignment:: 558* Address Clauses:: 559* Other Representation Clauses:: 560 561Tasking and Task-Related Features 562 563* Implementation of Tasks in HP Ada for OpenVMS Alpha Systems:: 564* Assigning Task IDs:: 565* Task IDs and Delays:: 566* Task-Related Pragmas:: 567* Scheduling and Task Priority:: 568* The Task Stack:: 569* External Interrupts:: 570 571Pragmas and Pragma-Related Features 572 573* Restrictions on the Pragma INLINE:: 574* Restrictions on the Pragma INTERFACE:: 575* Restrictions on the Pragma SYSTEM_NAME:: 576 577Library of Predefined Units 578 579* Changes to DECLIB:: 580 581Bindings 582 583* Shared Libraries and Options Files:: 584* Interfaces to C:: 585@end ifset 586 587Platform-Specific Information for the Run-Time Libraries 588 589* Summary of Run-Time Configurations:: 590* Specifying a Run-Time Library:: 591* Choosing the Scheduling Policy:: 592* Solaris-Specific Considerations:: 593* Linux-Specific Considerations:: 594* AIX-Specific Considerations:: 595* RTX-Specific Considerations:: 596* HP-UX-Specific Considerations:: 597 598Example of Binder Output File 599 600Elaboration Order Handling in GNAT 601 602* Elaboration Code:: 603* Checking the Elaboration Order:: 604* Controlling the Elaboration Order:: 605* Controlling Elaboration in GNAT - Internal Calls:: 606* Controlling Elaboration in GNAT - External Calls:: 607* Default Behavior in GNAT - Ensuring Safety:: 608* Treatment of Pragma Elaborate:: 609* Elaboration Issues for Library Tasks:: 610* Mixing Elaboration Models:: 611* What to Do If the Default Elaboration Behavior Fails:: 612* Elaboration for Dispatching Calls:: 613* Summary of Procedures for Elaboration Control:: 614* Other Elaboration Order Considerations:: 615 616Overflow Check Handling in GNAT 617* Background:: 618* Overflow Checking Modes in GNAT:: 619* Specifying the Desired Mode:: 620* Default Settings:: 621* Implementation Notes:: 622 623Conditional Compilation 624* Use of Boolean Constants:: 625* Debugging - A Special Case:: 626* Conditionalizing Declarations:: 627* Use of Alternative Implementations:: 628* Preprocessing:: 629 630Inline Assembler 631 632* Basic Assembler Syntax:: 633* A Simple Example of Inline Assembler:: 634* Output Variables in Inline Assembler:: 635* Input Variables in Inline Assembler:: 636* Inlining Inline Assembler Code:: 637* Other Asm Functionality:: 638 639Compatibility and Porting Guide 640 641* Compatibility with Ada 83:: 642* Compatibility between Ada 95 and Ada 2005:: 643* Implementation-dependent characteristics:: 644@ifclear vms 645@c This brief section is only in the non-VMS version 646@c The complete chapter on HP Ada issues is in the VMS version 647* Compatibility with HP Ada 83:: 648@end ifclear 649* Compatibility with Other Ada Systems:: 650* Representation Clauses:: 651@ifset vms 652* Transitioning to 64-Bit GNAT for OpenVMS:: 653@end ifset 654 655@ifset unw 656Microsoft Windows Topics 657 658* Using GNAT on Windows:: 659* CONSOLE and WINDOWS subsystems:: 660* Temporary Files:: 661* Mixed-Language Programming on Windows:: 662* Windows Calling Conventions:: 663* Introduction to Dynamic Link Libraries (DLLs):: 664* Using DLLs with GNAT:: 665* Building DLLs with GNAT:: 666* GNAT and Windows Resources:: 667* Debugging a DLL:: 668* Setting Stack Size from gnatlink:: 669* Setting Heap Size from gnatlink:: 670 671Mac OS Topics 672 673* Codesigning the Debugger:: 674@end ifset 675 676* Index:: 677@end menu 678@end ifnottex 679 680@node About This Guide 681@unnumbered About This Guide 682 683@noindent 684@ifset vms 685This guide describes the use of @value{EDITION}, 686a compiler and software development toolset for the full Ada 687programming language, implemented on OpenVMS for HP's Alpha and 688Integrity server (I64) platforms. 689@end ifset 690@ifclear vms 691This guide describes the use of @value{EDITION}, 692a compiler and software development 693toolset for the full Ada programming language. 694@end ifclear 695It documents the features of the compiler and tools, and explains 696how to use them to build Ada applications. 697 698@value{EDITION} implements Ada 95 and Ada 2005, and it may also be invoked in 699Ada 83 compatibility mode. 700By default, @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION}, 701but you can override with a compiler switch 702(@pxref{Compiling Different Versions of Ada}) 703to explicitly specify the language version. 704Throughout this manual, references to ``Ada'' without a year suffix 705apply to both the Ada 95 and Ada 2005 versions of the language. 706 707 708@ifclear FSFEDITION 709For ease of exposition, ``@value{EDITION}'' will be referred to simply as 710``GNAT'' in the remainder of this document. 711@end ifclear 712 713 714 715 716@menu 717* What This Guide Contains:: 718* What You Should Know before Reading This Guide:: 719* Related Information:: 720* Conventions:: 721@end menu 722 723@node What This Guide Contains 724@unnumberedsec What This Guide Contains 725 726@noindent 727This guide contains the following chapters: 728@itemize @bullet 729 730@item 731@ref{Getting Started with GNAT}, describes how to get started compiling 732and running Ada programs with the GNAT Ada programming environment. 733@item 734@ref{The GNAT Compilation Model}, describes the compilation model used 735by GNAT. 736 737@item 738@ref{Compiling Using gcc}, describes how to compile 739Ada programs with @command{gcc}, the Ada compiler. 740 741@item 742@ref{Binding Using gnatbind}, describes how to 743perform binding of Ada programs with @code{gnatbind}, the GNAT binding 744utility. 745 746@item 747@ref{Linking Using gnatlink}, 748describes @command{gnatlink}, a 749program that provides for linking using the GNAT run-time library to 750construct a program. @command{gnatlink} can also incorporate foreign language 751object units into the executable. 752 753@item 754@ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a 755utility that automatically determines the set of sources 756needed by an Ada compilation unit, and executes the necessary compilations 757binding and link. 758 759@item 760@ref{Improving Performance}, shows various techniques for making your 761Ada program run faster or take less space. 762It discusses the effect of the compiler's optimization switch and 763also describes the @command{gnatelim} tool and unused subprogram/data 764elimination. 765 766@item 767@ref{Renaming Files Using gnatchop}, describes 768@code{gnatchop}, a utility that allows you to preprocess a file that 769contains Ada source code, and split it into one or more new files, one 770for each compilation unit. 771 772@item 773@ref{Configuration Pragmas}, describes the configuration pragmas 774handled by GNAT. 775 776@item 777@ref{Handling Arbitrary File Naming Conventions Using gnatname}, 778shows how to override the default GNAT file naming conventions, 779either for an individual unit or globally. 780 781@item 782@ref{GNAT Project Manager}, describes how to use project files 783to organize large projects. 784 785@item 786@ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses 787@code{gnatxref} and @code{gnatfind}, two tools that provide an easy 788way to navigate through sources. 789 790@item 791@ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted 792version of an Ada source file with control over casing, indentation, 793comment placement, and other elements of program presentation style. 794 795@item 796@ref{The GNAT Metric Tool gnatmetric}, shows how to compute various 797metrics for an Ada source file, such as the number of types and subprograms, 798and assorted complexity measures. 799 800@item 801@ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr} 802file name krunching utility, used to handle shortened 803file names on operating systems with a limit on the length of names. 804 805@item 806@ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a 807preprocessor utility that allows a single source file to be used to 808generate multiple or parameterized source files by means of macro 809substitution. 810 811@item 812@ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a 813utility that displays information about compiled units, including dependences 814on the corresponding sources files, and consistency of compilations. 815 816@item 817@ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility 818to delete files that are produced by the compiler, binder and linker. 819 820@ifclear vms 821@item 822@ref{GNAT and Libraries}, describes the process of creating and using 823Libraries with GNAT. It also describes how to recompile the GNAT run-time 824library. 825 826@item 827@ref{Using the GNU make Utility}, describes some techniques for using 828the GNAT toolset in Makefiles. 829@end ifclear 830 831@item 832@ref{Memory Management Issues}, describes some useful predefined storage pools 833and in particular the GNAT Debug Pool facility, which helps detect incorrect 834memory references. 835@ifclear vms 836It also describes @command{gnatmem}, a utility that monitors dynamic 837allocation and deallocation and helps detect ``memory leaks''. 838@end ifclear 839 840@item 841@ref{Stack Related Facilities}, describes some useful tools associated with 842stack checking and analysis. 843 844@item 845@ref{Verifying Properties Using gnatcheck}, discusses @code{gnatcheck}, 846a utility that checks Ada code against a set of rules. 847 848@item 849@ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub}, 850a utility that generates empty but compilable bodies for library units. 851 852@item 853@ref{Creating Unit Tests Using gnattest}, discusses @code{gnattest}, 854a utility that generates unit testing templates for library units. 855 856@item 857@ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012 858facilities used in GNAT to declare dimensioned objects, and to verify that 859uses of these objects are consistent with their given physical dimensions 860(so that meters cannot be assigned to kilograms, and so on). 861 862@item 863@ref{Generating Ada Bindings for C and C++ headers}, describes how to 864generate automatically Ada bindings from C and C++ headers. 865 866@item 867@ref{Other Utility Programs}, discusses several other GNAT utilities, 868including @code{gnathtml}. 869 870@ifclear vms 871@item 872@ref{Code Coverage and Profiling}, describes how to perform a structural 873coverage and profile the execution of Ada programs. 874@end ifclear 875 876@item 877@ref{Running and Debugging Ada Programs}, describes how to run and debug 878Ada programs. 879 880@ifset vms 881@item 882@ref{Compatibility with HP Ada}, details the compatibility of GNAT with 883HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally 884developed by Digital Equipment Corporation and currently supported by HP.} 885for OpenVMS Alpha. This product was formerly known as DEC Ada, 886@cindex DEC Ada 887and for 888historical compatibility reasons, the relevant libraries still use the 889DEC prefix. 890@end ifset 891 892@item 893@ref{Platform-Specific Information for the Run-Time Libraries}, 894describes the various run-time 895libraries supported by GNAT on various platforms and explains how to 896choose a particular library. 897 898@item 899@ref{Example of Binder Output File}, shows the source code for the binder 900output file for a sample program. 901 902@item 903@ref{Elaboration Order Handling in GNAT}, describes how GNAT helps 904you deal with elaboration order issues. 905 906@item 907@ref{Overflow Check Handling in GNAT}, describes how GNAT helps 908you deal with arithmetic overflow issues. 909 910@item 911@ref{Conditional Compilation}, describes how to model conditional compilation, 912both with Ada in general and with GNAT facilities in particular. 913 914@item 915@ref{Inline Assembler}, shows how to use the inline assembly facility 916in an Ada program. 917 918@item 919@ref{Compatibility and Porting Guide}, contains sections on compatibility 920of GNAT with other Ada development environments (including Ada 83 systems), 921to assist in porting code from those environments. 922 923@ifset unw 924@item 925@ref{Microsoft Windows Topics}, presents information relevant to the 926Microsoft Windows platform. 927 928@item 929@ref{Mac OS Topics}, presents information relevant to Apple's OS X 930platform. 931@end ifset 932@end itemize 933 934@c ************************************************* 935@node What You Should Know before Reading This Guide 936@c ************************************************* 937@unnumberedsec What You Should Know before Reading This Guide 938 939@cindex Ada 95 Language Reference Manual 940@cindex Ada 2005 Language Reference Manual 941@noindent 942This guide assumes a basic familiarity with the Ada 95 language, as 943described in the International Standard ANSI/ISO/IEC-8652:1995, January 9441995. 945It does not require knowledge of the new features introduced by Ada 2005, 946(officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1 947and Amendment 1). 948Both reference manuals are included in the GNAT documentation 949package. 950 951@node Related Information 952@unnumberedsec Related Information 953 954@noindent 955For further information about related tools, refer to the following 956documents: 957 958@itemize @bullet 959@item 960@xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT 961Reference Manual}, which contains all reference material for the GNAT 962implementation of Ada. 963 964@ifset unw 965@item 966@cite{Using the GNAT Programming Studio}, which describes the GPS 967Integrated Development Environment. 968 969@item 970@cite{GNAT Programming Studio Tutorial}, which introduces the 971main GPS features through examples. 972@end ifset 973 974@item 975@cite{Ada 95 Reference Manual}, which contains reference 976material for the Ada 95 programming language. 977 978@item 979@cite{Ada 2005 Reference Manual}, which contains reference 980material for the Ada 2005 programming language. 981 982@item 983@xref{Top,, Debugging with GDB, gdb, Debugging with GDB}, 984@ifset vms 985in the GNU:[DOCS] directory, 986@end ifset 987for all details on the use of the GNU source-level debugger. 988 989@item 990@xref{Top,, The extensible self-documenting text editor, emacs, 991GNU Emacs Manual}, 992@ifset vms 993located in the GNU:[DOCS] directory if the EMACS kit is installed, 994@end ifset 995for full information on the extensible editor and programming 996environment Emacs. 997 998@end itemize 999 1000@c ************** 1001@node Conventions 1002@unnumberedsec Conventions 1003@cindex Conventions 1004@cindex Typographical conventions 1005 1006@noindent 1007Following are examples of the typographical and graphic conventions used 1008in this guide: 1009 1010@itemize @bullet 1011@item 1012@code{Functions}, @command{utility program names}, @code{standard names}, 1013and @code{classes}. 1014 1015@item 1016@option{Option flags} 1017 1018@item 1019@file{File names}, @samp{button names}, and @samp{field names}. 1020 1021@item 1022@code{Variables}, @env{environment variables}, and @var{metasyntactic 1023variables}. 1024 1025@item 1026@emph{Emphasis}. 1027 1028@item 1029@r{[}optional information or parameters@r{]} 1030 1031@item 1032Examples are described by text 1033@smallexample 1034and then shown this way. 1035@end smallexample 1036@end itemize 1037 1038@noindent 1039Commands that are entered by the user are preceded in this manual by the 1040characters @w{``@code{$ }''} (dollar sign followed by space). If your system 1041uses this sequence as a prompt, then the commands will appear exactly as 1042you see them in the manual. If your system uses some other prompt, then 1043the command will appear with the @code{$} replaced by whatever prompt 1044character you are using. 1045 1046@ifset unw 1047Full file names are shown with the ``@code{/}'' character 1048as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}. 1049If you are using GNAT on a Windows platform, please note that 1050the ``@code{\}'' character should be used instead. 1051@end ifset 1052 1053@c **************************** 1054@node Getting Started with GNAT 1055@chapter Getting Started with GNAT 1056 1057@noindent 1058This chapter describes some simple ways of using GNAT to build 1059executable Ada programs. 1060@ifset unw 1061@ref{Running GNAT}, through @ref{Using the gnatmake Utility}, 1062show how to use the command line environment. 1063@ref{Introduction to GPS}, provides a brief 1064introduction to the GNAT Programming Studio, a visually-oriented 1065Integrated Development Environment for GNAT. 1066GPS offers a graphical ``look and feel'', support for development in 1067other programming languages, comprehensive browsing features, and 1068many other capabilities. 1069For information on GPS please refer to 1070@cite{Using the GNAT Programming Studio}. 1071@end ifset 1072 1073@menu 1074* Running GNAT:: 1075* Running a Simple Ada Program:: 1076* Running a Program with Multiple Units:: 1077* Using the gnatmake Utility:: 1078@ifset vms 1079* Editing with Emacs:: 1080@end ifset 1081@ifclear vms 1082* Introduction to GPS:: 1083@end ifclear 1084@end menu 1085 1086@node Running GNAT 1087@section Running GNAT 1088 1089@noindent 1090Three steps are needed to create an executable file from an Ada source 1091file: 1092 1093@enumerate 1094@item 1095The source file(s) must be compiled. 1096@item 1097The file(s) must be bound using the GNAT binder. 1098@item 1099All appropriate object files must be linked to produce an executable. 1100@end enumerate 1101 1102@noindent 1103All three steps are most commonly handled by using the @command{gnatmake} 1104utility program that, given the name of the main program, automatically 1105performs the necessary compilation, binding and linking steps. 1106 1107@node Running a Simple Ada Program 1108@section Running a Simple Ada Program 1109 1110@noindent 1111Any text editor may be used to prepare an Ada program. 1112(If @code{Emacs} is 1113used, the optional Ada mode may be helpful in laying out the program.) 1114The 1115program text is a normal text file. We will assume in our initial 1116example that you have used your editor to prepare the following 1117standard format text file: 1118 1119@smallexample @c ada 1120@cartouche 1121with Ada.Text_IO; use Ada.Text_IO; 1122procedure Hello is 1123begin 1124 Put_Line ("Hello WORLD!"); 1125end Hello; 1126@end cartouche 1127@end smallexample 1128 1129@noindent 1130This file should be named @file{hello.adb}. 1131With the normal default file naming conventions, GNAT requires 1132that each file 1133contain a single compilation unit whose file name is the 1134unit name, 1135with periods replaced by hyphens; the 1136extension is @file{ads} for a 1137spec and @file{adb} for a body. 1138You can override this default file naming convention by use of the 1139special pragma @code{Source_File_Name} (@pxref{Using Other File Names}). 1140Alternatively, if you want to rename your files according to this default 1141convention, which is probably more convenient if you will be using GNAT 1142for all your compilations, then the @code{gnatchop} utility 1143can be used to generate correctly-named source files 1144(@pxref{Renaming Files Using gnatchop}). 1145 1146You can compile the program using the following command (@code{$} is used 1147as the command prompt in the examples in this document): 1148 1149@smallexample 1150$ gcc -c hello.adb 1151@end smallexample 1152 1153@noindent 1154@command{gcc} is the command used to run the compiler. This compiler is 1155capable of compiling programs in several languages, including Ada and 1156C. It assumes that you have given it an Ada program if the file extension is 1157either @file{.ads} or @file{.adb}, and it will then call 1158the GNAT compiler to compile the specified file. 1159 1160@ifclear vms 1161The @option{-c} switch is required. It tells @command{gcc} to only do a 1162compilation. (For C programs, @command{gcc} can also do linking, but this 1163capability is not used directly for Ada programs, so the @option{-c} 1164switch must always be present.) 1165@end ifclear 1166 1167This compile command generates a file 1168@file{hello.o}, which is the object 1169file corresponding to your Ada program. It also generates 1170an ``Ada Library Information'' file @file{hello.ali}, 1171which contains additional information used to check 1172that an Ada program is consistent. 1173To build an executable file, 1174use @code{gnatbind} to bind the program 1175and @command{gnatlink} to link it. The 1176argument to both @code{gnatbind} and @command{gnatlink} is the name of the 1177@file{ALI} file, but the default extension of @file{.ali} can 1178be omitted. This means that in the most common case, the argument 1179is simply the name of the main program: 1180 1181@smallexample 1182$ gnatbind hello 1183$ gnatlink hello 1184@end smallexample 1185 1186@noindent 1187A simpler method of carrying out these steps is to use 1188@command{gnatmake}, 1189a master program that invokes all the required 1190compilation, binding and linking tools in the correct order. In particular, 1191@command{gnatmake} automatically recompiles any sources that have been 1192modified since they were last compiled, or sources that depend 1193on such modified sources, so that ``version skew'' is avoided. 1194@cindex Version skew (avoided by @command{gnatmake}) 1195 1196@smallexample 1197$ gnatmake hello.adb 1198@end smallexample 1199 1200@noindent 1201The result is an executable program called @file{hello}, which can be 1202run by entering: 1203 1204@smallexample 1205$ ^hello^RUN HELLO^ 1206@end smallexample 1207 1208@noindent 1209assuming that the current directory is on the search path 1210for executable programs. 1211 1212@noindent 1213and, if all has gone well, you will see 1214 1215@smallexample 1216Hello WORLD! 1217@end smallexample 1218 1219@noindent 1220appear in response to this command. 1221 1222@c **************************************** 1223@node Running a Program with Multiple Units 1224@section Running a Program with Multiple Units 1225 1226@noindent 1227Consider a slightly more complicated example that has three files: a 1228main program, and the spec and body of a package: 1229 1230@smallexample @c ada 1231@cartouche 1232@group 1233package Greetings is 1234 procedure Hello; 1235 procedure Goodbye; 1236end Greetings; 1237 1238with Ada.Text_IO; use Ada.Text_IO; 1239package body Greetings is 1240 procedure Hello is 1241 begin 1242 Put_Line ("Hello WORLD!"); 1243 end Hello; 1244 1245 procedure Goodbye is 1246 begin 1247 Put_Line ("Goodbye WORLD!"); 1248 end Goodbye; 1249end Greetings; 1250@end group 1251 1252@group 1253with Greetings; 1254procedure Gmain is 1255begin 1256 Greetings.Hello; 1257 Greetings.Goodbye; 1258end Gmain; 1259@end group 1260@end cartouche 1261@end smallexample 1262 1263@noindent 1264Following the one-unit-per-file rule, place this program in the 1265following three separate files: 1266 1267@table @file 1268@item greetings.ads 1269spec of package @code{Greetings} 1270 1271@item greetings.adb 1272body of package @code{Greetings} 1273 1274@item gmain.adb 1275body of main program 1276@end table 1277 1278@noindent 1279To build an executable version of 1280this program, we could use four separate steps to compile, bind, and link 1281the program, as follows: 1282 1283@smallexample 1284$ gcc -c gmain.adb 1285$ gcc -c greetings.adb 1286$ gnatbind gmain 1287$ gnatlink gmain 1288@end smallexample 1289 1290@noindent 1291Note that there is no required order of compilation when using GNAT. 1292In particular it is perfectly fine to compile the main program first. 1293Also, it is not necessary to compile package specs in the case where 1294there is an accompanying body; you only need to compile the body. If you want 1295to submit these files to the compiler for semantic checking and not code 1296generation, then use the 1297@option{-gnatc} switch: 1298 1299@smallexample 1300$ gcc -c greetings.ads -gnatc 1301@end smallexample 1302 1303@noindent 1304Although the compilation can be done in separate steps as in the 1305above example, in practice it is almost always more convenient 1306to use the @command{gnatmake} tool. All you need to know in this case 1307is the name of the main program's source file. The effect of the above four 1308commands can be achieved with a single one: 1309 1310@smallexample 1311$ gnatmake gmain.adb 1312@end smallexample 1313 1314@noindent 1315In the next section we discuss the advantages of using @command{gnatmake} in 1316more detail. 1317 1318@c ***************************** 1319@node Using the gnatmake Utility 1320@section Using the @command{gnatmake} Utility 1321 1322@noindent 1323If you work on a program by compiling single components at a time using 1324@command{gcc}, you typically keep track of the units you modify. In order to 1325build a consistent system, you compile not only these units, but also any 1326units that depend on the units you have modified. 1327For example, in the preceding case, 1328if you edit @file{gmain.adb}, you only need to recompile that file. But if 1329you edit @file{greetings.ads}, you must recompile both 1330@file{greetings.adb} and @file{gmain.adb}, because both files contain 1331units that depend on @file{greetings.ads}. 1332 1333@code{gnatbind} will warn you if you forget one of these compilation 1334steps, so that it is impossible to generate an inconsistent program as a 1335result of forgetting to do a compilation. Nevertheless it is tedious and 1336error-prone to keep track of dependencies among units. 1337One approach to handle the dependency-bookkeeping is to use a 1338makefile. However, makefiles present maintenance problems of their own: 1339if the dependencies change as you change the program, you must make 1340sure that the makefile is kept up-to-date manually, which is also an 1341error-prone process. 1342 1343The @command{gnatmake} utility takes care of these details automatically. 1344Invoke it using either one of the following forms: 1345 1346@smallexample 1347$ gnatmake gmain.adb 1348$ gnatmake ^gmain^GMAIN^ 1349@end smallexample 1350 1351@noindent 1352The argument is the name of the file containing the main program; 1353you may omit the extension. @command{gnatmake} 1354examines the environment, automatically recompiles any files that need 1355recompiling, and binds and links the resulting set of object files, 1356generating the executable file, @file{^gmain^GMAIN.EXE^}. 1357In a large program, it 1358can be extremely helpful to use @command{gnatmake}, because working out by hand 1359what needs to be recompiled can be difficult. 1360 1361Note that @command{gnatmake} 1362takes into account all the Ada rules that 1363establish dependencies among units. These include dependencies that result 1364from inlining subprogram bodies, and from 1365generic instantiation. Unlike some other 1366Ada make tools, @command{gnatmake} does not rely on the dependencies that were 1367found by the compiler on a previous compilation, which may possibly 1368be wrong when sources change. @command{gnatmake} determines the exact set of 1369dependencies from scratch each time it is run. 1370 1371@ifset vms 1372@node Editing with Emacs 1373@section Editing with Emacs 1374@cindex Emacs 1375 1376@noindent 1377Emacs is an extensible self-documenting text editor that is available in a 1378separate VMSINSTAL kit. 1379 1380Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started, 1381click on the Emacs Help menu and run the Emacs Tutorial. 1382In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also 1383written as @kbd{C-h}), and the tutorial by @kbd{C-h t}. 1384 1385Documentation on Emacs and other tools is available in Emacs under the 1386pull-down menu button: @code{Help - Info}. After selecting @code{Info}, 1387use the middle mouse button to select a topic (e.g.@: Emacs). 1388 1389In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m} 1390(stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to 1391get to the Emacs manual. 1392Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command 1393prompt. 1394 1395The tutorial is highly recommended in order to learn the intricacies of Emacs, 1396which is sufficiently extensible to provide for a complete programming 1397environment and shell for the sophisticated user. 1398@end ifset 1399 1400@ifclear vms 1401@node Introduction to GPS 1402@section Introduction to GPS 1403@cindex GPS (GNAT Programming Studio) 1404@cindex GNAT Programming Studio (GPS) 1405@noindent 1406Although the command line interface (@command{gnatmake}, etc.) alone 1407is sufficient, a graphical Interactive Development 1408Environment can make it easier for you to compose, navigate, and debug 1409programs. This section describes the main features of GPS 1410(``GNAT Programming Studio''), the GNAT graphical IDE. 1411You will see how to use GPS to build and debug an executable, and 1412you will also learn some of the basics of the GNAT ``project'' facility. 1413 1414GPS enables you to do much more than is presented here; 1415e.g., you can produce a call graph, interface to a third-party 1416Version Control System, and inspect the generated assembly language 1417for a program. 1418Indeed, GPS also supports languages other than Ada. 1419Such additional information, and an explanation of all of the GPS menu 1420items. may be found in the on-line help, which includes 1421a user's guide and a tutorial (these are also accessible from the GNAT 1422startup menu). 1423 1424@menu 1425* Building a New Program with GPS:: 1426* Simple Debugging with GPS:: 1427@end menu 1428 1429@node Building a New Program with GPS 1430@subsection Building a New Program with GPS 1431@noindent 1432GPS invokes the GNAT compilation tools using information 1433contained in a @emph{project} (also known as a @emph{project file}): 1434a collection of properties such 1435as source directories, identities of main subprograms, tool switches, etc., 1436and their associated values. 1437See @ref{GNAT Project Manager} for details. 1438In order to run GPS, you will need to either create a new project 1439or else open an existing one. 1440 1441This section will explain how you can use GPS to create a project, 1442to associate Ada source files with a project, and to build and run 1443programs. 1444 1445@enumerate 1446@item @emph{Creating a project} 1447 1448Invoke GPS, either from the command line or the platform's IDE. 1449After it starts, GPS will display a ``Welcome'' screen with three 1450radio buttons: 1451 1452@itemize @bullet 1453@item 1454@code{Start with default project in directory} 1455 1456@item 1457@code{Create new project with wizard} 1458 1459@item 1460@code{Open existing project} 1461@end itemize 1462 1463@noindent 1464Select @code{Create new project with wizard} and press @code{OK}. 1465A new window will appear. In the text box labeled with 1466@code{Enter the name of the project to create}, type @file{sample} 1467as the project name. 1468In the next box, browse to choose the directory in which you 1469would like to create the project file. 1470After selecting an appropriate directory, press @code{Forward}. 1471 1472A window will appear with the title 1473@code{Version Control System Configuration}. 1474Simply press @code{Forward}. 1475 1476A window will appear with the title 1477@code{Please select the source directories for this project}. 1478The directory that you specified for the project file will be selected 1479by default as the one to use for sources; simply press @code{Forward}. 1480 1481A window will appear with the title 1482@code{Please select the build directory for this project}. 1483The directory that you specified for the project file will be selected 1484by default for object files and executables; 1485simply press @code{Forward}. 1486 1487A window will appear with the title 1488@code{Please select the main units for this project}. 1489You will supply this information later, after creating the source file. 1490Simply press @code{Forward} for now. 1491 1492A window will appear with the title 1493@code{Please select the switches to build the project}. 1494Press @code{Apply}. This will create a project file named 1495@file{sample.prj} in the directory that you had specified. 1496 1497@item @emph{Creating and saving the source file} 1498 1499After you create the new project, a GPS window will appear, which is 1500partitioned into two main sections: 1501 1502@itemize @bullet 1503@item 1504A @emph{Workspace area}, initially greyed out, which you will use for 1505creating and editing source files 1506 1507@item 1508Directly below, a @emph{Messages area}, which initially displays a 1509``Welcome'' message. 1510(If the Messages area is not visible, drag its border upward to expand it.) 1511@end itemize 1512 1513@noindent 1514Select @code{File} on the menu bar, and then the @code{New} command. 1515The Workspace area will become white, and you can now 1516enter the source program explicitly. 1517Type the following text 1518 1519@smallexample @c ada 1520@group 1521with Ada.Text_IO; use Ada.Text_IO; 1522procedure Hello is 1523begin 1524 Put_Line("Hello from GPS!"); 1525end Hello; 1526@end group 1527@end smallexample 1528 1529@noindent 1530Select @code{File}, then @code{Save As}, and enter the source file name 1531@file{hello.adb}. 1532The file will be saved in the same directory you specified as the 1533location of the default project file. 1534 1535@item @emph{Updating the project file} 1536 1537You need to add the new source file to the project. 1538To do this, select 1539the @code{Project} menu and then @code{Edit project properties}. 1540Click the @code{Main files} tab on the left, and then the 1541@code{Add} button. 1542Choose @file{hello.adb} from the list, and press @code{Open}. 1543The project settings window will reflect this action. 1544Click @code{OK}. 1545 1546@item @emph{Building and running the program} 1547 1548In the main GPS window, now choose the @code{Build} menu, then @code{Make}, 1549and select @file{hello.adb}. 1550The Messages window will display the resulting invocations of @command{gcc}, 1551@command{gnatbind}, and @command{gnatlink} 1552(reflecting the default switch settings from the 1553project file that you created) and then a ``successful compilation/build'' 1554message. 1555 1556To run the program, choose the @code{Build} menu, then @code{Run}, and 1557select @command{hello}. 1558An @emph{Arguments Selection} window will appear. 1559There are no command line arguments, so just click @code{OK}. 1560 1561The Messages window will now display the program's output (the string 1562@code{Hello from GPS}), and at the bottom of the GPS window a status 1563update is displayed (@code{Run: hello}). 1564Close the GPS window (or select @code{File}, then @code{Exit}) to 1565terminate this GPS session. 1566@end enumerate 1567 1568@node Simple Debugging with GPS 1569@subsection Simple Debugging with GPS 1570@noindent 1571This section illustrates basic debugging techniques (setting breakpoints, 1572examining/modifying variables, single stepping). 1573 1574@enumerate 1575@item @emph{Opening a project} 1576 1577Start GPS and select @code{Open existing project}; browse to 1578specify the project file @file{sample.prj} that you had created in the 1579earlier example. 1580 1581@item @emph{Creating a source file} 1582 1583Select @code{File}, then @code{New}, and type in the following program: 1584 1585@smallexample @c ada 1586@group 1587with Ada.Text_IO; use Ada.Text_IO; 1588procedure Example is 1589 Line : String (1..80); 1590 N : Natural; 1591begin 1592 Put_Line("Type a line of text at each prompt; an empty line to exit"); 1593 loop 1594 Put(": "); 1595 Get_Line (Line, N); 1596 Put_Line (Line (1..N) ); 1597 exit when N=0; 1598 end loop; 1599end Example; 1600@end group 1601@end smallexample 1602 1603@noindent 1604Select @code{File}, then @code{Save as}, and enter the file name 1605@file{example.adb}. 1606 1607@item @emph{Updating the project file} 1608 1609Add @code{Example} as a new main unit for the project: 1610@enumerate a 1611@item 1612Select @code{Project}, then @code{Edit Project Properties}. 1613 1614@item 1615Select the @code{Main files} tab, click @code{Add}, then 1616select the file @file{example.adb} from the list, and 1617click @code{Open}. 1618You will see the file name appear in the list of main units 1619 1620@item 1621Click @code{OK} 1622@end enumerate 1623 1624@item @emph{Building/running the executable} 1625 1626To build the executable 1627select @code{Build}, then @code{Make}, and then choose @file{example.adb}. 1628 1629Run the program to see its effect (in the Messages area). 1630Each line that you enter is displayed; an empty line will 1631cause the loop to exit and the program to terminate. 1632 1633@item @emph{Debugging the program} 1634 1635Note that the @option{-g} switches to @command{gcc} and @command{gnatlink}, 1636which are required for debugging, are on by default when you create 1637a new project. 1638Thus unless you intentionally remove these settings, you will be able 1639to debug any program that you develop using GPS. 1640 1641@enumerate a 1642@item @emph{Initializing} 1643 1644Select @code{Debug}, then @code{Initialize}, then @file{example} 1645 1646@item @emph{Setting a breakpoint} 1647 1648After performing the initialization step, you will observe a small 1649icon to the right of each line number. 1650This serves as a toggle for breakpoints; clicking the icon will 1651set a breakpoint at the corresponding line (the icon will change to 1652a red circle with an ``x''), and clicking it again 1653will remove the breakpoint / reset the icon. 1654 1655For purposes of this example, set a breakpoint at line 10 (the 1656statement @code{Put_Line@ (Line@ (1..N));} 1657 1658@item @emph{Starting program execution} 1659 1660Select @code{Debug}, then @code{Run}. When the 1661@code{Program Arguments} window appears, click @code{OK}. 1662A console window will appear; enter some line of text, 1663e.g.@: @code{abcde}, at the prompt. 1664The program will pause execution when it gets to the 1665breakpoint, and the corresponding line is highlighted. 1666 1667@item @emph{Examining a variable} 1668 1669Move the mouse over one of the occurrences of the variable @code{N}. 1670You will see the value (5) displayed, in ``tool tip'' fashion. 1671Right click on @code{N}, select @code{Debug}, then select @code{Display N}. 1672You will see information about @code{N} appear in the @code{Debugger Data} 1673pane, showing the value as 5. 1674 1675@item @emph{Assigning a new value to a variable} 1676 1677Right click on the @code{N} in the @code{Debugger Data} pane, and 1678select @code{Set value of N}. 1679When the input window appears, enter the value @code{4} and click 1680@code{OK}. 1681This value does not automatically appear in the @code{Debugger Data} 1682pane; to see it, right click again on the @code{N} in the 1683@code{Debugger Data} pane and select @code{Update value}. 1684The new value, 4, will appear in red. 1685 1686@item @emph{Single stepping} 1687 1688Select @code{Debug}, then @code{Next}. 1689This will cause the next statement to be executed, in this case the 1690call of @code{Put_Line} with the string slice. 1691Notice in the console window that the displayed string is simply 1692@code{abcd} and not @code{abcde} which you had entered. 1693This is because the upper bound of the slice is now 4 rather than 5. 1694 1695@item @emph{Removing a breakpoint} 1696 1697Toggle the breakpoint icon at line 10. 1698 1699@item @emph{Resuming execution from a breakpoint} 1700 1701Select @code{Debug}, then @code{Continue}. 1702The program will reach the next iteration of the loop, and 1703wait for input after displaying the prompt. 1704This time, just hit the @kbd{Enter} key. 1705The value of @code{N} will be 0, and the program will terminate. 1706The console window will disappear. 1707@end enumerate 1708@end enumerate 1709@end ifclear 1710 1711@node The GNAT Compilation Model 1712@chapter The GNAT Compilation Model 1713@cindex GNAT compilation model 1714@cindex Compilation model 1715 1716@menu 1717* Source Representation:: 1718* Foreign Language Representation:: 1719* File Naming Rules:: 1720* Using Other File Names:: 1721* Alternative File Naming Schemes:: 1722* Generating Object Files:: 1723* Source Dependencies:: 1724* The Ada Library Information Files:: 1725* Binding an Ada Program:: 1726* Mixed Language Programming:: 1727@ifclear vms 1728* Building Mixed Ada & C++ Programs:: 1729* Comparison between GNAT and C/C++ Compilation Models:: 1730@end ifclear 1731* Comparison between GNAT and Conventional Ada Library Models:: 1732@ifset vms 1733* Placement of temporary files:: 1734@end ifset 1735@end menu 1736 1737@noindent 1738This chapter describes the compilation model used by GNAT. Although 1739similar to that used by other languages, such as C and C++, this model 1740is substantially different from the traditional Ada compilation models, 1741which are based on a library. The model is initially described without 1742reference to the library-based model. If you have not previously used an 1743Ada compiler, you need only read the first part of this chapter. The 1744last section describes and discusses the differences between the GNAT 1745model and the traditional Ada compiler models. If you have used other 1746Ada compilers, this section will help you to understand those 1747differences, and the advantages of the GNAT model. 1748 1749@node Source Representation 1750@section Source Representation 1751@cindex Latin-1 1752 1753@noindent 1754Ada source programs are represented in standard text files, using 1755Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar 17567-bit ASCII set, plus additional characters used for 1757representing foreign languages (@pxref{Foreign Language Representation} 1758for support of non-USA character sets). The format effector characters 1759are represented using their standard ASCII encodings, as follows: 1760 1761@table @code 1762@item VT 1763@findex VT 1764Vertical tab, @code{16#0B#} 1765 1766@item HT 1767@findex HT 1768Horizontal tab, @code{16#09#} 1769 1770@item CR 1771@findex CR 1772Carriage return, @code{16#0D#} 1773 1774@item LF 1775@findex LF 1776Line feed, @code{16#0A#} 1777 1778@item FF 1779@findex FF 1780Form feed, @code{16#0C#} 1781@end table 1782 1783@noindent 1784Source files are in standard text file format. In addition, GNAT will 1785recognize a wide variety of stream formats, in which the end of 1786physical lines is marked by any of the following sequences: 1787@code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful 1788in accommodating files that are imported from other operating systems. 1789 1790@cindex End of source file 1791@cindex Source file, end 1792@findex SUB 1793The end of a source file is normally represented by the physical end of 1794file. However, the control character @code{16#1A#} (@code{SUB}) is also 1795recognized as signalling the end of the source file. Again, this is 1796provided for compatibility with other operating systems where this 1797code is used to represent the end of file. 1798 1799Each file contains a single Ada compilation unit, including any pragmas 1800associated with the unit. For example, this means you must place a 1801package declaration (a package @dfn{spec}) and the corresponding body in 1802separate files. An Ada @dfn{compilation} (which is a sequence of 1803compilation units) is represented using a sequence of files. Similarly, 1804you will place each subunit or child unit in a separate file. 1805 1806@node Foreign Language Representation 1807@section Foreign Language Representation 1808 1809@noindent 1810GNAT supports the standard character sets defined in Ada as well as 1811several other non-standard character sets for use in localized versions 1812of the compiler (@pxref{Character Set Control}). 1813@menu 1814* Latin-1:: 1815* Other 8-Bit Codes:: 1816* Wide Character Encodings:: 1817@end menu 1818 1819@node Latin-1 1820@subsection Latin-1 1821@cindex Latin-1 1822 1823@noindent 1824The basic character set is Latin-1. This character set is defined by ISO 1825standard 8859, part 1. The lower half (character codes @code{16#00#} 1826@dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper 1827half is used to represent additional characters. These include extended letters 1828used by European languages, such as French accents, the vowels with umlauts 1829used in German, and the extra letter A-ring used in Swedish. 1830 1831@findex Ada.Characters.Latin_1 1832For a complete list of Latin-1 codes and their encodings, see the source 1833file of library unit @code{Ada.Characters.Latin_1} in file 1834@file{a-chlat1.ads}. 1835You may use any of these extended characters freely in character or 1836string literals. In addition, the extended characters that represent 1837letters can be used in identifiers. 1838 1839@node Other 8-Bit Codes 1840@subsection Other 8-Bit Codes 1841 1842@noindent 1843GNAT also supports several other 8-bit coding schemes: 1844 1845@table @asis 1846@item ISO 8859-2 (Latin-2) 1847@cindex Latin-2 1848@cindex ISO 8859-2 1849Latin-2 letters allowed in identifiers, with uppercase and lowercase 1850equivalence. 1851 1852@item ISO 8859-3 (Latin-3) 1853@cindex Latin-3 1854@cindex ISO 8859-3 1855Latin-3 letters allowed in identifiers, with uppercase and lowercase 1856equivalence. 1857 1858@item ISO 8859-4 (Latin-4) 1859@cindex Latin-4 1860@cindex ISO 8859-4 1861Latin-4 letters allowed in identifiers, with uppercase and lowercase 1862equivalence. 1863 1864@item ISO 8859-5 (Cyrillic) 1865@cindex ISO 8859-5 1866@cindex Cyrillic 1867ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and 1868lowercase equivalence. 1869 1870@item ISO 8859-15 (Latin-9) 1871@cindex ISO 8859-15 1872@cindex Latin-9 1873ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and 1874lowercase equivalence 1875 1876@item IBM PC (code page 437) 1877@cindex code page 437 1878This code page is the normal default for PCs in the U.S. It corresponds 1879to the original IBM PC character set. This set has some, but not all, of 1880the extended Latin-1 letters, but these letters do not have the same 1881encoding as Latin-1. In this mode, these letters are allowed in 1882identifiers with uppercase and lowercase equivalence. 1883 1884@item IBM PC (code page 850) 1885@cindex code page 850 1886This code page is a modification of 437 extended to include all the 1887Latin-1 letters, but still not with the usual Latin-1 encoding. In this 1888mode, all these letters are allowed in identifiers with uppercase and 1889lowercase equivalence. 1890 1891@item Full Upper 8-bit 1892Any character in the range 80-FF allowed in identifiers, and all are 1893considered distinct. In other words, there are no uppercase and lowercase 1894equivalences in this range. This is useful in conjunction with 1895certain encoding schemes used for some foreign character sets (e.g., 1896the typical method of representing Chinese characters on the PC). 1897 1898@item No Upper-Half 1899No upper-half characters in the range 80-FF are allowed in identifiers. 1900This gives Ada 83 compatibility for identifier names. 1901@end table 1902 1903@noindent 1904For precise data on the encodings permitted, and the uppercase and lowercase 1905equivalences that are recognized, see the file @file{csets.adb} in 1906the GNAT compiler sources. You will need to obtain a full source release 1907of GNAT to obtain this file. 1908 1909@node Wide Character Encodings 1910@subsection Wide Character Encodings 1911 1912@noindent 1913GNAT allows wide character codes to appear in character and string 1914literals, and also optionally in identifiers, by means of the following 1915possible encoding schemes: 1916 1917@table @asis 1918 1919@item Hex Coding 1920In this encoding, a wide character is represented by the following five 1921character sequence: 1922 1923@smallexample 1924ESC a b c d 1925@end smallexample 1926 1927@noindent 1928Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal 1929characters (using uppercase letters) of the wide character code. For 1930example, ESC A345 is used to represent the wide character with code 1931@code{16#A345#}. 1932This scheme is compatible with use of the full Wide_Character set. 1933 1934@item Upper-Half Coding 1935@cindex Upper-Half Coding 1936The wide character with encoding @code{16#abcd#} where the upper bit is on 1937(in other words, ``a'' is in the range 8-F) is represented as two bytes, 1938@code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control 1939character, but is not required to be in the upper half. This method can 1940be also used for shift-JIS or EUC, where the internal coding matches the 1941external coding. 1942 1943@item Shift JIS Coding 1944@cindex Shift JIS Coding 1945A wide character is represented by a two-character sequence, 1946@code{16#ab#} and 1947@code{16#cd#}, with the restrictions described for upper-half encoding as 1948described above. The internal character code is the corresponding JIS 1949character according to the standard algorithm for Shift-JIS 1950conversion. Only characters defined in the JIS code set table can be 1951used with this encoding method. 1952 1953@item EUC Coding 1954@cindex EUC Coding 1955A wide character is represented by a two-character sequence 1956@code{16#ab#} and 1957@code{16#cd#}, with both characters being in the upper half. The internal 1958character code is the corresponding JIS character according to the EUC 1959encoding algorithm. Only characters defined in the JIS code set table 1960can be used with this encoding method. 1961 1962@item UTF-8 Coding 1963A wide character is represented using 1964UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO 196510646-1/Am.2. Depending on the character value, the representation 1966is a one, two, or three byte sequence: 1967@smallexample 1968@iftex 1969@leftskip=.7cm 1970@end iftex 197116#0000#-16#007f#: 2#0@var{xxxxxxx}# 197216#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}# 197316#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}# 1974 1975@end smallexample 1976 1977@noindent 1978where the @var{xxx} bits correspond to the left-padded bits of the 197916-bit character value. Note that all lower half ASCII characters 1980are represented as ASCII bytes and all upper half characters and 1981other wide characters are represented as sequences of upper-half 1982(The full UTF-8 scheme allows for encoding 31-bit characters as 19836-byte sequences, but in this implementation, all UTF-8 sequences 1984of four or more bytes length will be treated as illegal). 1985@item Brackets Coding 1986In this encoding, a wide character is represented by the following eight 1987character sequence: 1988 1989@smallexample 1990[ " a b c d " ] 1991@end smallexample 1992 1993@noindent 1994Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal 1995characters (using uppercase letters) of the wide character code. For 1996example, [``A345''] is used to represent the wide character with code 1997@code{16#A345#}. It is also possible (though not required) to use the 1998Brackets coding for upper half characters. For example, the code 1999@code{16#A3#} can be represented as @code{[``A3'']}. 2000 2001This scheme is compatible with use of the full Wide_Character set, 2002and is also the method used for wide character encoding in the standard 2003ACVC (Ada Compiler Validation Capability) test suite distributions. 2004 2005@end table 2006 2007@noindent 2008Note: Some of these coding schemes do not permit the full use of the 2009Ada character set. For example, neither Shift JIS, nor EUC allow the 2010use of the upper half of the Latin-1 set. 2011 2012@node File Naming Rules 2013@section File Naming Rules 2014 2015@noindent 2016The default file name is determined by the name of the unit that the 2017file contains. The name is formed by taking the full expanded name of 2018the unit and replacing the separating dots with hyphens and using 2019^lowercase^uppercase^ for all letters. 2020 2021An exception arises if the file name generated by the above rules starts 2022with one of the characters 2023@ifset vms 2024@samp{A}, @samp{G}, @samp{I}, or @samp{S}, 2025@end ifset 2026@ifclear vms 2027@samp{a}, @samp{g}, @samp{i}, or @samp{s}, 2028@end ifclear 2029and the second character is a 2030minus. In this case, the character ^tilde^dollar sign^ is used in place 2031of the minus. The reason for this special rule is to avoid clashes with 2032the standard names for child units of the packages System, Ada, 2033Interfaces, and GNAT, which use the prefixes 2034@ifset vms 2035@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-}, 2036@end ifset 2037@ifclear vms 2038@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-}, 2039@end ifclear 2040respectively. 2041 2042The file extension is @file{.ads} for a spec and 2043@file{.adb} for a body. The following list shows some 2044examples of these rules. 2045 2046@table @file 2047@item main.ads 2048Main (spec) 2049@item main.adb 2050Main (body) 2051@item arith_functions.ads 2052Arith_Functions (package spec) 2053@item arith_functions.adb 2054Arith_Functions (package body) 2055@item func-spec.ads 2056Func.Spec (child package spec) 2057@item func-spec.adb 2058Func.Spec (child package body) 2059@item main-sub.adb 2060Sub (subunit of Main) 2061@item ^a~bad.adb^A$BAD.ADB^ 2062A.Bad (child package body) 2063@end table 2064 2065@noindent 2066Following these rules can result in excessively long 2067file names if corresponding 2068unit names are long (for example, if child units or subunits are 2069heavily nested). An option is available to shorten such long file names 2070(called file name ``krunching''). This may be particularly useful when 2071programs being developed with GNAT are to be used on operating systems 2072with limited file name lengths. @xref{Using gnatkr}. 2073 2074Of course, no file shortening algorithm can guarantee uniqueness over 2075all possible unit names; if file name krunching is used, it is your 2076responsibility to ensure no name clashes occur. Alternatively you 2077can specify the exact file names that you want used, as described 2078in the next section. Finally, if your Ada programs are migrating from a 2079compiler with a different naming convention, you can use the gnatchop 2080utility to produce source files that follow the GNAT naming conventions. 2081(For details @pxref{Renaming Files Using gnatchop}.) 2082 2083Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating 2084systems, case is not significant. So for example on @code{Windows XP} 2085if the canonical name is @code{main-sub.adb}, you can use the file name 2086@code{Main-Sub.adb} instead. However, case is significant for other 2087operating systems, so for example, if you want to use other than 2088canonically cased file names on a Unix system, you need to follow 2089the procedures described in the next section. 2090 2091@node Using Other File Names 2092@section Using Other File Names 2093@cindex File names 2094 2095@noindent 2096In the previous section, we have described the default rules used by 2097GNAT to determine the file name in which a given unit resides. It is 2098often convenient to follow these default rules, and if you follow them, 2099the compiler knows without being explicitly told where to find all 2100the files it needs. 2101 2102However, in some cases, particularly when a program is imported from 2103another Ada compiler environment, it may be more convenient for the 2104programmer to specify which file names contain which units. GNAT allows 2105arbitrary file names to be used by means of the Source_File_Name pragma. 2106The form of this pragma is as shown in the following examples: 2107@cindex Source_File_Name pragma 2108 2109@smallexample @c ada 2110@cartouche 2111pragma Source_File_Name (My_Utilities.Stacks, 2112 Spec_File_Name => "myutilst_a.ada"); 2113pragma Source_File_name (My_Utilities.Stacks, 2114 Body_File_Name => "myutilst.ada"); 2115@end cartouche 2116@end smallexample 2117 2118@noindent 2119As shown in this example, the first argument for the pragma is the unit 2120name (in this example a child unit). The second argument has the form 2121of a named association. The identifier 2122indicates whether the file name is for a spec or a body; 2123the file name itself is given by a string literal. 2124 2125The source file name pragma is a configuration pragma, which means that 2126normally it will be placed in the @file{gnat.adc} 2127file used to hold configuration 2128pragmas that apply to a complete compilation environment. 2129For more details on how the @file{gnat.adc} file is created and used 2130see @ref{Handling of Configuration Pragmas}. 2131@cindex @file{gnat.adc} 2132 2133@ifclear vms 2134GNAT allows completely arbitrary file names to be specified using the 2135source file name pragma. However, if the file name specified has an 2136extension other than @file{.ads} or @file{.adb} it is necessary to use 2137a special syntax when compiling the file. The name in this case must be 2138preceded by the special sequence @option{-x} followed by a space and the name 2139of the language, here @code{ada}, as in: 2140 2141@smallexample 2142$ gcc -c -x ada peculiar_file_name.sim 2143@end smallexample 2144@end ifclear 2145 2146@noindent 2147@command{gnatmake} handles non-standard file names in the usual manner (the 2148non-standard file name for the main program is simply used as the 2149argument to gnatmake). Note that if the extension is also non-standard, 2150then it must be included in the @command{gnatmake} command, it may not 2151be omitted. 2152 2153@node Alternative File Naming Schemes 2154@section Alternative File Naming Schemes 2155@cindex File naming schemes, alternative 2156@cindex File names 2157 2158In the previous section, we described the use of the @code{Source_File_Name} 2159pragma to allow arbitrary names to be assigned to individual source files. 2160However, this approach requires one pragma for each file, and especially in 2161large systems can result in very long @file{gnat.adc} files, and also create 2162a maintenance problem. 2163 2164GNAT also provides a facility for specifying systematic file naming schemes 2165other than the standard default naming scheme previously described. An 2166alternative scheme for naming is specified by the use of 2167@code{Source_File_Name} pragmas having the following format: 2168@cindex Source_File_Name pragma 2169 2170@smallexample @c ada 2171pragma Source_File_Name ( 2172 Spec_File_Name => FILE_NAME_PATTERN 2173 @r{[},Casing => CASING_SPEC@r{]} 2174 @r{[},Dot_Replacement => STRING_LITERAL@r{]}); 2175 2176pragma Source_File_Name ( 2177 Body_File_Name => FILE_NAME_PATTERN 2178 @r{[},Casing => CASING_SPEC@r{]} 2179 @r{[},Dot_Replacement => STRING_LITERAL@r{]}); 2180 2181pragma Source_File_Name ( 2182 Subunit_File_Name => FILE_NAME_PATTERN 2183 @r{[},Casing => CASING_SPEC@r{]} 2184 @r{[},Dot_Replacement => STRING_LITERAL@r{]}); 2185 2186FILE_NAME_PATTERN ::= STRING_LITERAL 2187CASING_SPEC ::= Lowercase | Uppercase | Mixedcase 2188@end smallexample 2189 2190@noindent 2191The @code{FILE_NAME_PATTERN} string shows how the file name is constructed. 2192It contains a single asterisk character, and the unit name is substituted 2193systematically for this asterisk. The optional parameter 2194@code{Casing} indicates 2195whether the unit name is to be all upper-case letters, all lower-case letters, 2196or mixed-case. If no 2197@code{Casing} parameter is used, then the default is all 2198^lower-case^upper-case^. 2199 2200The optional @code{Dot_Replacement} string is used to replace any periods 2201that occur in subunit or child unit names. If no @code{Dot_Replacement} 2202argument is used then separating dots appear unchanged in the resulting 2203file name. 2204Although the above syntax indicates that the 2205@code{Casing} argument must appear 2206before the @code{Dot_Replacement} argument, but it 2207is also permissible to write these arguments in the opposite order. 2208 2209As indicated, it is possible to specify different naming schemes for 2210bodies, specs, and subunits. Quite often the rule for subunits is the 2211same as the rule for bodies, in which case, there is no need to give 2212a separate @code{Subunit_File_Name} rule, and in this case the 2213@code{Body_File_name} rule is used for subunits as well. 2214 2215The separate rule for subunits can also be used to implement the rather 2216unusual case of a compilation environment (e.g.@: a single directory) which 2217contains a subunit and a child unit with the same unit name. Although 2218both units cannot appear in the same partition, the Ada Reference Manual 2219allows (but does not require) the possibility of the two units coexisting 2220in the same environment. 2221 2222The file name translation works in the following steps: 2223 2224@itemize @bullet 2225 2226@item 2227If there is a specific @code{Source_File_Name} pragma for the given unit, 2228then this is always used, and any general pattern rules are ignored. 2229 2230@item 2231If there is a pattern type @code{Source_File_Name} pragma that applies to 2232the unit, then the resulting file name will be used if the file exists. If 2233more than one pattern matches, the latest one will be tried first, and the 2234first attempt resulting in a reference to a file that exists will be used. 2235 2236@item 2237If no pattern type @code{Source_File_Name} pragma that applies to the unit 2238for which the corresponding file exists, then the standard GNAT default 2239naming rules are used. 2240 2241@end itemize 2242 2243@noindent 2244As an example of the use of this mechanism, consider a commonly used scheme 2245in which file names are all lower case, with separating periods copied 2246unchanged to the resulting file name, and specs end with @file{.1.ada}, and 2247bodies end with @file{.2.ada}. GNAT will follow this scheme if the following 2248two pragmas appear: 2249 2250@smallexample @c ada 2251pragma Source_File_Name 2252 (Spec_File_Name => "*.1.ada"); 2253pragma Source_File_Name 2254 (Body_File_Name => "*.2.ada"); 2255@end smallexample 2256 2257@noindent 2258The default GNAT scheme is actually implemented by providing the following 2259default pragmas internally: 2260 2261@smallexample @c ada 2262pragma Source_File_Name 2263 (Spec_File_Name => "*.ads", Dot_Replacement => "-"); 2264pragma Source_File_Name 2265 (Body_File_Name => "*.adb", Dot_Replacement => "-"); 2266@end smallexample 2267 2268@noindent 2269Our final example implements a scheme typically used with one of the 2270Ada 83 compilers, where the separator character for subunits was ``__'' 2271(two underscores), specs were identified by adding @file{_.ADA}, bodies 2272by adding @file{.ADA}, and subunits by 2273adding @file{.SEP}. All file names were 2274upper case. Child units were not present of course since this was an 2275Ada 83 compiler, but it seems reasonable to extend this scheme to use 2276the same double underscore separator for child units. 2277 2278@smallexample @c ada 2279pragma Source_File_Name 2280 (Spec_File_Name => "*_.ADA", 2281 Dot_Replacement => "__", 2282 Casing = Uppercase); 2283pragma Source_File_Name 2284 (Body_File_Name => "*.ADA", 2285 Dot_Replacement => "__", 2286 Casing = Uppercase); 2287pragma Source_File_Name 2288 (Subunit_File_Name => "*.SEP", 2289 Dot_Replacement => "__", 2290 Casing = Uppercase); 2291@end smallexample 2292 2293@node Generating Object Files 2294@section Generating Object Files 2295 2296@noindent 2297An Ada program consists of a set of source files, and the first step in 2298compiling the program is to generate the corresponding object files. 2299These are generated by compiling a subset of these source files. 2300The files you need to compile are the following: 2301 2302@itemize @bullet 2303@item 2304If a package spec has no body, compile the package spec to produce the 2305object file for the package. 2306 2307@item 2308If a package has both a spec and a body, compile the body to produce the 2309object file for the package. The source file for the package spec need 2310not be compiled in this case because there is only one object file, which 2311contains the code for both the spec and body of the package. 2312 2313@item 2314For a subprogram, compile the subprogram body to produce the object file 2315for the subprogram. The spec, if one is present, is as usual in a 2316separate file, and need not be compiled. 2317 2318@item 2319@cindex Subunits 2320In the case of subunits, only compile the parent unit. A single object 2321file is generated for the entire subunit tree, which includes all the 2322subunits. 2323 2324@item 2325Compile child units independently of their parent units 2326(though, of course, the spec of all the ancestor unit must be present in order 2327to compile a child unit). 2328 2329@item 2330@cindex Generics 2331Compile generic units in the same manner as any other units. The object 2332files in this case are small dummy files that contain at most the 2333flag used for elaboration checking. This is because GNAT always handles generic 2334instantiation by means of macro expansion. However, it is still necessary to 2335compile generic units, for dependency checking and elaboration purposes. 2336@end itemize 2337 2338@noindent 2339The preceding rules describe the set of files that must be compiled to 2340generate the object files for a program. Each object file has the same 2341name as the corresponding source file, except that the extension is 2342@file{.o} as usual. 2343 2344You may wish to compile other files for the purpose of checking their 2345syntactic and semantic correctness. For example, in the case where a 2346package has a separate spec and body, you would not normally compile the 2347spec. However, it is convenient in practice to compile the spec to make 2348sure it is error-free before compiling clients of this spec, because such 2349compilations will fail if there is an error in the spec. 2350 2351GNAT provides an option for compiling such files purely for the 2352purposes of checking correctness; such compilations are not required as 2353part of the process of building a program. To compile a file in this 2354checking mode, use the @option{-gnatc} switch. 2355 2356@node Source Dependencies 2357@section Source Dependencies 2358 2359@noindent 2360A given object file clearly depends on the source file which is compiled 2361to produce it. Here we are using @dfn{depends} in the sense of a typical 2362@code{make} utility; in other words, an object file depends on a source 2363file if changes to the source file require the object file to be 2364recompiled. 2365In addition to this basic dependency, a given object may depend on 2366additional source files as follows: 2367 2368@itemize @bullet 2369@item 2370If a file being compiled @code{with}'s a unit @var{X}, the object file 2371depends on the file containing the spec of unit @var{X}. This includes 2372files that are @code{with}'ed implicitly either because they are parents 2373of @code{with}'ed child units or they are run-time units required by the 2374language constructs used in a particular unit. 2375 2376@item 2377If a file being compiled instantiates a library level generic unit, the 2378object file depends on both the spec and body files for this generic 2379unit. 2380 2381@item 2382If a file being compiled instantiates a generic unit defined within a 2383package, the object file depends on the body file for the package as 2384well as the spec file. 2385 2386@item 2387@findex Inline 2388@cindex @option{-gnatn} switch 2389If a file being compiled contains a call to a subprogram for which 2390pragma @code{Inline} applies and inlining is activated with the 2391@option{-gnatn} switch, the object file depends on the file containing the 2392body of this subprogram as well as on the file containing the spec. Note 2393that for inlining to actually occur as a result of the use of this switch, 2394it is necessary to compile in optimizing mode. 2395 2396@cindex @option{-gnatN} switch 2397The use of @option{-gnatN} activates inlining optimization 2398that is performed by the front end of the compiler. This inlining does 2399not require that the code generation be optimized. Like @option{-gnatn}, 2400the use of this switch generates additional dependencies. 2401 2402When using a gcc-based back end (in practice this means using any version 2403of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of 2404@option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred. 2405Historically front end inlining was more extensive than the gcc back end 2406inlining, but that is no longer the case. 2407 2408@item 2409If an object file @file{O} depends on the proper body of a subunit through 2410inlining or instantiation, it depends on the parent unit of the subunit. 2411This means that any modification of the parent unit or one of its subunits 2412affects the compilation of @file{O}. 2413 2414@item 2415The object file for a parent unit depends on all its subunit body files. 2416 2417@item 2418The previous two rules meant that for purposes of computing dependencies and 2419recompilation, a body and all its subunits are treated as an indivisible whole. 2420 2421@noindent 2422These rules are applied transitively: if unit @code{A} @code{with}'s 2423unit @code{B}, whose elaboration calls an inlined procedure in package 2424@code{C}, the object file for unit @code{A} will depend on the body of 2425@code{C}, in file @file{c.adb}. 2426 2427The set of dependent files described by these rules includes all the 2428files on which the unit is semantically dependent, as dictated by the 2429Ada language standard. However, it is a superset of what the 2430standard describes, because it includes generic, inline, and subunit 2431dependencies. 2432 2433An object file must be recreated by recompiling the corresponding source 2434file if any of the source files on which it depends are modified. For 2435example, if the @code{make} utility is used to control compilation, 2436the rule for an Ada object file must mention all the source files on 2437which the object file depends, according to the above definition. 2438The determination of the necessary 2439recompilations is done automatically when one uses @command{gnatmake}. 2440@end itemize 2441 2442@node The Ada Library Information Files 2443@section The Ada Library Information Files 2444@cindex Ada Library Information files 2445@cindex @file{ALI} files 2446 2447@noindent 2448Each compilation actually generates two output files. The first of these 2449is the normal object file that has a @file{.o} extension. The second is a 2450text file containing full dependency information. It has the same 2451name as the source file, but an @file{.ali} extension. 2452This file is known as the Ada Library Information (@file{ALI}) file. 2453The following information is contained in the @file{ALI} file. 2454 2455@itemize @bullet 2456@item 2457Version information (indicates which version of GNAT was used to compile 2458the unit(s) in question) 2459 2460@item 2461Main program information (including priority and time slice settings, 2462as well as the wide character encoding used during compilation). 2463 2464@item 2465List of arguments used in the @command{gcc} command for the compilation 2466 2467@item 2468Attributes of the unit, including configuration pragmas used, an indication 2469of whether the compilation was successful, exception model used etc. 2470 2471@item 2472A list of relevant restrictions applying to the unit (used for consistency) 2473checking. 2474 2475@item 2476Categorization information (e.g.@: use of pragma @code{Pure}). 2477 2478@item 2479Information on all @code{with}'ed units, including presence of 2480@code{Elaborate} or @code{Elaborate_All} pragmas. 2481 2482@item 2483Information from any @code{Linker_Options} pragmas used in the unit 2484 2485@item 2486Information on the use of @code{Body_Version} or @code{Version} 2487attributes in the unit. 2488 2489@item 2490Dependency information. This is a list of files, together with 2491time stamp and checksum information. These are files on which 2492the unit depends in the sense that recompilation is required 2493if any of these units are modified. 2494 2495@item 2496Cross-reference data. Contains information on all entities referenced 2497in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to 2498provide cross-reference information. 2499 2500@end itemize 2501 2502@noindent 2503For a full detailed description of the format of the @file{ALI} file, 2504see the source of the body of unit @code{Lib.Writ}, contained in file 2505@file{lib-writ.adb} in the GNAT compiler sources. 2506 2507@node Binding an Ada Program 2508@section Binding an Ada Program 2509 2510@noindent 2511When using languages such as C and C++, once the source files have been 2512compiled the only remaining step in building an executable program 2513is linking the object modules together. This means that it is possible to 2514link an inconsistent version of a program, in which two units have 2515included different versions of the same header. 2516 2517The rules of Ada do not permit such an inconsistent program to be built. 2518For example, if two clients have different versions of the same package, 2519it is illegal to build a program containing these two clients. 2520These rules are enforced by the GNAT binder, which also determines an 2521elaboration order consistent with the Ada rules. 2522 2523The GNAT binder is run after all the object files for a program have 2524been created. It is given the name of the main program unit, and from 2525this it determines the set of units required by the program, by reading the 2526corresponding ALI files. It generates error messages if the program is 2527inconsistent or if no valid order of elaboration exists. 2528 2529If no errors are detected, the binder produces a main program, in Ada by 2530default, that contains calls to the elaboration procedures of those 2531compilation unit that require them, followed by 2532a call to the main program. This Ada program is compiled to generate the 2533object file for the main program. The name of 2534the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec 2535@file{b~@var{xxx}.ads}) where @var{xxx} is the name of the 2536main program unit. 2537 2538Finally, the linker is used to build the resulting executable program, 2539using the object from the main program from the bind step as well as the 2540object files for the Ada units of the program. 2541 2542@node Mixed Language Programming 2543@section Mixed Language Programming 2544@cindex Mixed Language Programming 2545 2546@noindent 2547This section describes how to develop a mixed-language program, 2548specifically one that comprises units in both Ada and C. 2549 2550@menu 2551* Interfacing to C:: 2552* Calling Conventions:: 2553@end menu 2554 2555@node Interfacing to C 2556@subsection Interfacing to C 2557@noindent 2558Interfacing Ada with a foreign language such as C involves using 2559compiler directives to import and/or export entity definitions in each 2560language---using @code{extern} statements in C, for instance, and the 2561@code{Import}, @code{Export}, and @code{Convention} pragmas in Ada. 2562A full treatment of these topics is provided in Appendix B, section 1 2563of the Ada Reference Manual. 2564 2565There are two ways to build a program using GNAT that contains some Ada 2566sources and some foreign language sources, depending on whether or not 2567the main subprogram is written in Ada. Here is a source example with 2568the main subprogram in Ada: 2569 2570@smallexample 2571/* file1.c */ 2572#include <stdio.h> 2573 2574void print_num (int num) 2575@{ 2576 printf ("num is %d.\n", num); 2577 return; 2578@} 2579 2580/* file2.c */ 2581 2582/* num_from_Ada is declared in my_main.adb */ 2583extern int num_from_Ada; 2584 2585int get_num (void) 2586@{ 2587 return num_from_Ada; 2588@} 2589@end smallexample 2590 2591@smallexample @c ada 2592-- my_main.adb 2593procedure My_Main is 2594 2595 -- Declare then export an Integer entity called num_from_Ada 2596 My_Num : Integer := 10; 2597 pragma Export (C, My_Num, "num_from_Ada"); 2598 2599 -- Declare an Ada function spec for Get_Num, then use 2600 -- C function get_num for the implementation. 2601 function Get_Num return Integer; 2602 pragma Import (C, Get_Num, "get_num"); 2603 2604 -- Declare an Ada procedure spec for Print_Num, then use 2605 -- C function print_num for the implementation. 2606 procedure Print_Num (Num : Integer); 2607 pragma Import (C, Print_Num, "print_num"); 2608 2609begin 2610 Print_Num (Get_Num); 2611end My_Main; 2612@end smallexample 2613 2614@enumerate 2615@item 2616To build this example, first compile the foreign language files to 2617generate object files: 2618@smallexample 2619^gcc -c file1.c^gcc -c FILE1.C^ 2620^gcc -c file2.c^gcc -c FILE2.C^ 2621@end smallexample 2622 2623@item 2624Then, compile the Ada units to produce a set of object files and ALI 2625files: 2626@smallexample 2627gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb 2628@end smallexample 2629 2630@item 2631Run the Ada binder on the Ada main program: 2632@smallexample 2633gnatbind my_main.ali 2634@end smallexample 2635 2636@item 2637Link the Ada main program, the Ada objects and the other language 2638objects: 2639@smallexample 2640gnatlink my_main.ali file1.o file2.o 2641@end smallexample 2642@end enumerate 2643 2644The last three steps can be grouped in a single command: 2645@smallexample 2646gnatmake my_main.adb -largs file1.o file2.o 2647@end smallexample 2648 2649@cindex Binder output file 2650@noindent 2651If the main program is in a language other than Ada, then you may have 2652more than one entry point into the Ada subsystem. You must use a special 2653binder option to generate callable routines that initialize and 2654finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}). 2655Calls to the initialization and finalization routines must be inserted 2656in the main program, or some other appropriate point in the code. The 2657call to initialize the Ada units must occur before the first Ada 2658subprogram is called, and the call to finalize the Ada units must occur 2659after the last Ada subprogram returns. The binder will place the 2660initialization and finalization subprograms into the 2661@file{b~@var{xxx}.adb} file where they can be accessed by your C 2662sources. To illustrate, we have the following example: 2663 2664@smallexample 2665/* main.c */ 2666extern void adainit (void); 2667extern void adafinal (void); 2668extern int add (int, int); 2669extern int sub (int, int); 2670 2671int main (int argc, char *argv[]) 2672@{ 2673 int a = 21, b = 7; 2674 2675 adainit(); 2676 2677 /* Should print "21 + 7 = 28" */ 2678 printf ("%d + %d = %d\n", a, b, add (a, b)); 2679 /* Should print "21 - 7 = 14" */ 2680 printf ("%d - %d = %d\n", a, b, sub (a, b)); 2681 2682 adafinal(); 2683@} 2684@end smallexample 2685 2686@smallexample @c ada 2687-- unit1.ads 2688package Unit1 is 2689 function Add (A, B : Integer) return Integer; 2690 pragma Export (C, Add, "add"); 2691end Unit1; 2692 2693-- unit1.adb 2694package body Unit1 is 2695 function Add (A, B : Integer) return Integer is 2696 begin 2697 return A + B; 2698 end Add; 2699end Unit1; 2700 2701-- unit2.ads 2702package Unit2 is 2703 function Sub (A, B : Integer) return Integer; 2704 pragma Export (C, Sub, "sub"); 2705end Unit2; 2706 2707-- unit2.adb 2708package body Unit2 is 2709 function Sub (A, B : Integer) return Integer is 2710 begin 2711 return A - B; 2712 end Sub; 2713end Unit2; 2714@end smallexample 2715 2716@enumerate 2717@item 2718The build procedure for this application is similar to the last 2719example's. First, compile the foreign language files to generate object 2720files: 2721@smallexample 2722^gcc -c main.c^gcc -c main.c^ 2723@end smallexample 2724 2725@item 2726Next, compile the Ada units to produce a set of object files and ALI 2727files: 2728@smallexample 2729gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb 2730gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb 2731@end smallexample 2732 2733@item 2734Run the Ada binder on every generated ALI file. Make sure to use the 2735@option{-n} option to specify a foreign main program: 2736@smallexample 2737gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali 2738@end smallexample 2739 2740@item 2741Link the Ada main program, the Ada objects and the foreign language 2742objects. You need only list the last ALI file here: 2743@smallexample 2744gnatlink unit2.ali main.o -o exec_file 2745@end smallexample 2746 2747This procedure yields a binary executable called @file{exec_file}. 2748@end enumerate 2749 2750@noindent 2751Depending on the circumstances (for example when your non-Ada main object 2752does not provide symbol @code{main}), you may also need to instruct the 2753GNAT linker not to include the standard startup objects by passing the 2754@option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}. 2755 2756@node Calling Conventions 2757@subsection Calling Conventions 2758@cindex Foreign Languages 2759@cindex Calling Conventions 2760GNAT follows standard calling sequence conventions and will thus interface 2761to any other language that also follows these conventions. The following 2762Convention identifiers are recognized by GNAT: 2763 2764@table @code 2765@cindex Interfacing to Ada 2766@cindex Other Ada compilers 2767@cindex Convention Ada 2768@item Ada 2769This indicates that the standard Ada calling sequence will be 2770used and all Ada data items may be passed without any limitations in the 2771case where GNAT is used to generate both the caller and callee. It is also 2772possible to mix GNAT generated code and code generated by another Ada 2773compiler. In this case, the data types should be restricted to simple 2774cases, including primitive types. Whether complex data types can be passed 2775depends on the situation. Probably it is safe to pass simple arrays, such 2776as arrays of integers or floats. Records may or may not work, depending 2777on whether both compilers lay them out identically. Complex structures 2778involving variant records, access parameters, tasks, or protected types, 2779are unlikely to be able to be passed. 2780 2781Note that in the case of GNAT running 2782on a platform that supports HP Ada 83, a higher degree of compatibility 2783can be guaranteed, and in particular records are layed out in an identical 2784manner in the two compilers. Note also that if output from two different 2785compilers is mixed, the program is responsible for dealing with elaboration 2786issues. Probably the safest approach is to write the main program in the 2787version of Ada other than GNAT, so that it takes care of its own elaboration 2788requirements, and then call the GNAT-generated adainit procedure to ensure 2789elaboration of the GNAT components. Consult the documentation of the other 2790Ada compiler for further details on elaboration. 2791 2792However, it is not possible to mix the tasking run time of GNAT and 2793HP Ada 83, All the tasking operations must either be entirely within 2794GNAT compiled sections of the program, or entirely within HP Ada 83 2795compiled sections of the program. 2796 2797@cindex Interfacing to Assembly 2798@cindex Convention Assembler 2799@item Assembler 2800Specifies assembler as the convention. In practice this has the 2801same effect as convention Ada (but is not equivalent in the sense of being 2802considered the same convention). 2803 2804@cindex Convention Asm 2805@findex Asm 2806@item Asm 2807Equivalent to Assembler. 2808 2809@cindex Interfacing to COBOL 2810@cindex Convention COBOL 2811@findex COBOL 2812@item COBOL 2813Data will be passed according to the conventions described 2814in section B.4 of the Ada Reference Manual. 2815 2816@findex C 2817@cindex Interfacing to C 2818@cindex Convention C 2819@item C 2820Data will be passed according to the conventions described 2821in section B.3 of the Ada Reference Manual. 2822 2823A note on interfacing to a C ``varargs'' function: 2824@findex C varargs function 2825@cindex Interfacing to C varargs function 2826@cindex varargs function interfaces 2827 2828@itemize @bullet 2829@item 2830In C, @code{varargs} allows a function to take a variable number of 2831arguments. There is no direct equivalent in this to Ada. One 2832approach that can be used is to create a C wrapper for each 2833different profile and then interface to this C wrapper. For 2834example, to print an @code{int} value using @code{printf}, 2835create a C function @code{printfi} that takes two arguments, a 2836pointer to a string and an int, and calls @code{printf}. 2837Then in the Ada program, use pragma @code{Import} to 2838interface to @code{printfi}. 2839 2840@item 2841It may work on some platforms to directly interface to 2842a @code{varargs} function by providing a specific Ada profile 2843for a particular call. However, this does not work on 2844all platforms, since there is no guarantee that the 2845calling sequence for a two argument normal C function 2846is the same as for calling a @code{varargs} C function with 2847the same two arguments. 2848@end itemize 2849 2850@cindex Convention Default 2851@findex Default 2852@item Default 2853Equivalent to C. 2854 2855@cindex Convention External 2856@findex External 2857@item External 2858Equivalent to C. 2859 2860@ifclear vms 2861@findex C++ 2862@cindex Interfacing to C++ 2863@cindex Convention C++ 2864@item C_Plus_Plus (or CPP) 2865This stands for C++. For most purposes this is identical to C. 2866See the separate description of the specialized GNAT pragmas relating to 2867C++ interfacing for further details. 2868@end ifclear 2869 2870@findex Fortran 2871@cindex Interfacing to Fortran 2872@cindex Convention Fortran 2873@item Fortran 2874Data will be passed according to the conventions described 2875in section B.5 of the Ada Reference Manual. 2876 2877@item Intrinsic 2878This applies to an intrinsic operation, as defined in the Ada 2879Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram, 2880this means that the body of the subprogram is provided by the compiler itself, 2881usually by means of an efficient code sequence, and that the user does not 2882supply an explicit body for it. In an application program, the pragma may 2883be applied to the following sets of names: 2884 2885@itemize @bullet 2886@item 2887Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, 2888Shift_Right_Arithmetic. The corresponding subprogram declaration must have 2889two formal parameters. The 2890first one must be a signed integer type or a modular type with a binary 2891modulus, and the second parameter must be of type Natural. 2892The return type must be the same as the type of the first argument. The size 2893of this type can only be 8, 16, 32, or 64. 2894 2895@item 2896Binary arithmetic operators: ``+'', ``-'', ``*'', ``/'' 2897The corresponding operator declaration must have parameters and result type 2898that have the same root numeric type (for example, all three are long_float 2899types). This simplifies the definition of operations that use type checking 2900to perform dimensional checks: 2901 2902@smallexample @c ada 2903type Distance is new Long_Float; 2904type Time is new Long_Float; 2905type Velocity is new Long_Float; 2906function "/" (D : Distance; T : Time) 2907 return Velocity; 2908pragma Import (Intrinsic, "/"); 2909@end smallexample 2910 2911@noindent 2912This common idiom is often programmed with a generic definition and an 2913explicit body. The pragma makes it simpler to introduce such declarations. 2914It incurs no overhead in compilation time or code size, because it is 2915implemented as a single machine instruction. 2916 2917@item 2918General subprogram entities, to bind an Ada subprogram declaration to 2919a compiler builtin by name with back-ends where such interfaces are 2920available. A typical example is the set of ``__builtin'' functions 2921exposed by the GCC back-end, as in the following example: 2922 2923@smallexample @c ada 2924 function builtin_sqrt (F : Float) return Float; 2925 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf"); 2926@end smallexample 2927 2928Most of the GCC builtins are accessible this way, and as for other 2929import conventions (e.g. C), it is the user's responsibility to ensure 2930that the Ada subprogram profile matches the underlying builtin 2931expectations. 2932@end itemize 2933 2934@noindent 2935 2936@ifset unw 2937@findex Stdcall 2938@cindex Convention Stdcall 2939@item Stdcall 2940This is relevant only to Windows XP/2000/NT implementations of GNAT, 2941and specifies that the @code{Stdcall} calling sequence will be used, 2942as defined by the NT API. Nevertheless, to ease building 2943cross-platform bindings this convention will be handled as a @code{C} calling 2944convention on non-Windows platforms. 2945 2946@findex DLL 2947@cindex Convention DLL 2948@item DLL 2949This is equivalent to @code{Stdcall}. 2950 2951@findex Win32 2952@cindex Convention Win32 2953@item Win32 2954This is equivalent to @code{Stdcall}. 2955@end ifset 2956 2957@findex Stubbed 2958@cindex Convention Stubbed 2959@item Stubbed 2960This is a special convention that indicates that the compiler 2961should provide a stub body that raises @code{Program_Error}. 2962@end table 2963 2964@noindent 2965GNAT additionally provides a useful pragma @code{Convention_Identifier} 2966that can be used to parameterize conventions and allow additional synonyms 2967to be specified. For example if you have legacy code in which the convention 2968identifier Fortran77 was used for Fortran, you can use the configuration 2969pragma: 2970 2971@smallexample @c ada 2972pragma Convention_Identifier (Fortran77, Fortran); 2973@end smallexample 2974 2975@noindent 2976And from now on the identifier Fortran77 may be used as a convention 2977identifier (for example in an @code{Import} pragma) with the same 2978meaning as Fortran. 2979 2980@ifclear vms 2981@node Building Mixed Ada & C++ Programs 2982@section Building Mixed Ada and C++ Programs 2983 2984@noindent 2985A programmer inexperienced with mixed-language development may find that 2986building an application containing both Ada and C++ code can be a 2987challenge. This section gives a few 2988hints that should make this task easier. The first section addresses 2989the differences between interfacing with C and interfacing with C++. 2990The second section 2991looks into the delicate problem of linking the complete application from 2992its Ada and C++ parts. The last section gives some hints on how the GNAT 2993run-time library can be adapted in order to allow inter-language dispatching 2994with a new C++ compiler. 2995 2996@menu 2997* Interfacing to C++:: 2998* Linking a Mixed C++ & Ada Program:: 2999* A Simple Example:: 3000* Interfacing with C++ constructors:: 3001* Interfacing with C++ at the Class Level:: 3002@end menu 3003 3004@node Interfacing to C++ 3005@subsection Interfacing to C++ 3006 3007@noindent 3008GNAT supports interfacing with the G++ compiler (or any C++ compiler 3009generating code that is compatible with the G++ Application Binary 3010Interface ---see http://www.codesourcery.com/archives/cxx-abi). 3011 3012@noindent 3013Interfacing can be done at 3 levels: simple data, subprograms, and 3014classes. In the first two cases, GNAT offers a specific @code{Convention 3015C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}. 3016Usually, C++ mangles the names of subprograms. To generate proper mangled 3017names automatically, see @ref{Generating Ada Bindings for C and C++ headers}). 3018This problem can also be addressed manually in two ways: 3019 3020@itemize @bullet 3021@item 3022by modifying the C++ code in order to force a C convention using 3023the @code{extern "C"} syntax. 3024 3025@item 3026by figuring out the mangled name (using e.g. @command{nm}) and using it as the 3027Link_Name argument of the pragma import. 3028@end itemize 3029 3030@noindent 3031Interfacing at the class level can be achieved by using the GNAT specific 3032pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,, 3033gnat_rm, GNAT Reference Manual}, for additional information. 3034 3035@node Linking a Mixed C++ & Ada Program 3036@subsection Linking a Mixed C++ & Ada Program 3037 3038@noindent 3039Usually the linker of the C++ development system must be used to link 3040mixed applications because most C++ systems will resolve elaboration 3041issues (such as calling constructors on global class instances) 3042transparently during the link phase. GNAT has been adapted to ease the 3043use of a foreign linker for the last phase. Three cases can be 3044considered: 3045@enumerate 3046 3047@item 3048Using GNAT and G++ (GNU C++ compiler) from the same GCC installation: 3049The C++ linker can simply be called by using the C++ specific driver 3050called @code{g++}. 3051 3052Note that if the C++ code uses inline functions, you will need to 3053compile your C++ code with the @code{-fkeep-inline-functions} switch in 3054order to provide an existing function implementation that the Ada code can 3055link with. 3056 3057@smallexample 3058$ g++ -c -fkeep-inline-functions file1.C 3059$ g++ -c -fkeep-inline-functions file2.C 3060$ gnatmake ada_unit -largs file1.o file2.o --LINK=g++ 3061@end smallexample 3062 3063@item 3064Using GNAT and G++ from two different GCC installations: If both 3065compilers are on the @env{PATH}, the previous method may be used. It is 3066important to note that environment variables such as 3067@env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and 3068@env{GCC_ROOT} will affect both compilers 3069at the same time and may make one of the two compilers operate 3070improperly if set during invocation of the wrong compiler. It is also 3071very important that the linker uses the proper @file{libgcc.a} GCC 3072library -- that is, the one from the C++ compiler installation. The 3073implicit link command as suggested in the @command{gnatmake} command 3074from the former example can be replaced by an explicit link command with 3075the full-verbosity option in order to verify which library is used: 3076@smallexample 3077$ gnatbind ada_unit 3078$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ 3079@end smallexample 3080If there is a problem due to interfering environment variables, it can 3081be worked around by using an intermediate script. The following example 3082shows the proper script to use when GNAT has not been installed at its 3083default location and g++ has been installed at its default location: 3084 3085@smallexample 3086$ cat ./my_script 3087#!/bin/sh 3088unset BINUTILS_ROOT 3089unset GCC_ROOT 3090c++ $* 3091$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script 3092@end smallexample 3093 3094@item 3095Using a non-GNU C++ compiler: The commands previously described can be 3096used to insure that the C++ linker is used. Nonetheless, you need to add 3097a few more parameters to the link command line, depending on the exception 3098mechanism used. 3099 3100If the @code{setjmp/longjmp} exception mechanism is used, only the paths 3101to the libgcc libraries are required: 3102 3103@smallexample 3104$ cat ./my_script 3105#!/bin/sh 3106CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` 3107$ gnatlink ada_unit file1.o file2.o --LINK=./my_script 3108@end smallexample 3109 3110Where CC is the name of the non-GNU C++ compiler. 3111 3112If the @code{zero cost} exception mechanism is used, and the platform 3113supports automatic registration of exception tables (e.g.@: Solaris), 3114paths to more objects are required: 3115 3116@smallexample 3117$ cat ./my_script 3118#!/bin/sh 3119CC `gcc -print-file-name=crtbegin.o` $* \ 3120`gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \ 3121`gcc -print-file-name=crtend.o` 3122$ gnatlink ada_unit file1.o file2.o --LINK=./my_script 3123@end smallexample 3124 3125If the @code{zero cost} exception mechanism is used, and the platform 3126doesn't support automatic registration of exception tables (e.g.@: HP-UX 3127or AIX), the simple approach described above will not work and 3128a pre-linking phase using GNAT will be necessary. 3129 3130@end enumerate 3131 3132Another alternative is to use the @command{gprbuild} multi-language builder 3133which has a large knowledge base and knows how to link Ada and C++ code 3134together automatically in most cases. 3135 3136@node A Simple Example 3137@subsection A Simple Example 3138@noindent 3139The following example, provided as part of the GNAT examples, shows how 3140to achieve procedural interfacing between Ada and C++ in both 3141directions. The C++ class A has two methods. The first method is exported 3142to Ada by the means of an extern C wrapper function. The second method 3143calls an Ada subprogram. On the Ada side, The C++ calls are modelled by 3144a limited record with a layout comparable to the C++ class. The Ada 3145subprogram, in turn, calls the C++ method. So, starting from the C++ 3146main program, the process passes back and forth between the two 3147languages. 3148 3149@noindent 3150Here are the compilation commands: 3151@smallexample 3152$ gnatmake -c simple_cpp_interface 3153$ g++ -c cpp_main.C 3154$ g++ -c ex7.C 3155$ gnatbind -n simple_cpp_interface 3156$ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ 3157 -lstdc++ ex7.o cpp_main.o 3158@end smallexample 3159 3160@noindent 3161Here are the corresponding sources: 3162@smallexample 3163 3164//cpp_main.C 3165 3166#include "ex7.h" 3167 3168extern "C" @{ 3169 void adainit (void); 3170 void adafinal (void); 3171 void method1 (A *t); 3172@} 3173 3174void method1 (A *t) 3175@{ 3176 t->method1 (); 3177@} 3178 3179int main () 3180@{ 3181 A obj; 3182 adainit (); 3183 obj.method2 (3030); 3184 adafinal (); 3185@} 3186 3187//ex7.h 3188 3189class Origin @{ 3190 public: 3191 int o_value; 3192@}; 3193class A : public Origin @{ 3194 public: 3195 void method1 (void); 3196 void method2 (int v); 3197 A(); 3198 int a_value; 3199@}; 3200 3201//ex7.C 3202 3203#include "ex7.h" 3204#include <stdio.h> 3205 3206extern "C" @{ void ada_method2 (A *t, int v);@} 3207 3208void A::method1 (void) 3209@{ 3210 a_value = 2020; 3211 printf ("in A::method1, a_value = %d \n",a_value); 3212 3213@} 3214 3215void A::method2 (int v) 3216@{ 3217 ada_method2 (this, v); 3218 printf ("in A::method2, a_value = %d \n",a_value); 3219 3220@} 3221 3222A::A(void) 3223@{ 3224 a_value = 1010; 3225 printf ("in A::A, a_value = %d \n",a_value); 3226@} 3227@end smallexample 3228 3229@smallexample @c ada 3230-- Ada sources 3231package body Simple_Cpp_Interface is 3232 3233 procedure Ada_Method2 (This : in out A; V : Integer) is 3234 begin 3235 Method1 (This); 3236 This.A_Value := V; 3237 end Ada_Method2; 3238 3239end Simple_Cpp_Interface; 3240 3241with System; 3242package Simple_Cpp_Interface is 3243 type A is limited 3244 record 3245 Vptr : System.Address; 3246 O_Value : Integer; 3247 A_Value : Integer; 3248 end record; 3249 pragma Convention (C, A); 3250 3251 procedure Method1 (This : in out A); 3252 pragma Import (C, Method1); 3253 3254 procedure Ada_Method2 (This : in out A; V : Integer); 3255 pragma Export (C, Ada_Method2); 3256 3257end Simple_Cpp_Interface; 3258@end smallexample 3259 3260@node Interfacing with C++ constructors 3261@subsection Interfacing with C++ constructors 3262@noindent 3263 3264In order to interface with C++ constructors GNAT provides the 3265@code{pragma CPP_Constructor} (@xref{Interfacing to C++,,, 3266gnat_rm, GNAT Reference Manual}, for additional information). 3267In this section we present some common uses of C++ constructors 3268in mixed-languages programs in GNAT. 3269 3270Let us assume that we need to interface with the following 3271C++ class: 3272 3273@smallexample 3274@b{class} Root @{ 3275@b{public}: 3276 int a_value; 3277 int b_value; 3278 @b{virtual} int Get_Value (); 3279 Root(); // Default constructor 3280 Root(int v); // 1st non-default constructor 3281 Root(int v, int w); // 2nd non-default constructor 3282@}; 3283@end smallexample 3284 3285For this purpose we can write the following package spec (further 3286information on how to build this spec is available in 3287@ref{Interfacing with C++ at the Class Level} and 3288@ref{Generating Ada Bindings for C and C++ headers}). 3289 3290@smallexample @c ada 3291with Interfaces.C; use Interfaces.C; 3292package Pkg_Root is 3293 type Root is tagged limited record 3294 A_Value : int; 3295 B_Value : int; 3296 end record; 3297 pragma Import (CPP, Root); 3298 3299 function Get_Value (Obj : Root) return int; 3300 pragma Import (CPP, Get_Value); 3301 3302 function Constructor return Root; 3303 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev"); 3304 3305 function Constructor (v : Integer) return Root; 3306 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei"); 3307 3308 function Constructor (v, w : Integer) return Root; 3309 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii"); 3310end Pkg_Root; 3311@end smallexample 3312 3313On the Ada side the constructor is represented by a function (whose 3314name is arbitrary) that returns the classwide type corresponding to 3315the imported C++ class. Although the constructor is described as a 3316function, it is typically a procedure with an extra implicit argument 3317(the object being initialized) at the implementation level. GNAT 3318issues the appropriate call, whatever it is, to get the object 3319properly initialized. 3320 3321Constructors can only appear in the following contexts: 3322 3323@itemize @bullet 3324@item 3325On the right side of an initialization of an object of type @var{T}. 3326@item 3327On the right side of an initialization of a record component of type @var{T}. 3328@item 3329In an Ada 2005 limited aggregate. 3330@item 3331In an Ada 2005 nested limited aggregate. 3332@item 3333In an Ada 2005 limited aggregate that initializes an object built in 3334place by an extended return statement. 3335@end itemize 3336 3337@noindent 3338In a declaration of an object whose type is a class imported from C++, 3339either the default C++ constructor is implicitly called by GNAT, or 3340else the required C++ constructor must be explicitly called in the 3341expression that initializes the object. For example: 3342 3343@smallexample @c ada 3344 Obj1 : Root; 3345 Obj2 : Root := Constructor; 3346 Obj3 : Root := Constructor (v => 10); 3347 Obj4 : Root := Constructor (30, 40); 3348@end smallexample 3349 3350The first two declarations are equivalent: in both cases the default C++ 3351constructor is invoked (in the former case the call to the constructor is 3352implicit, and in the latter case the call is explicit in the object 3353declaration). @code{Obj3} is initialized by the C++ non-default constructor 3354that takes an integer argument, and @code{Obj4} is initialized by the 3355non-default C++ constructor that takes two integers. 3356 3357Let us derive the imported C++ class in the Ada side. For example: 3358 3359@smallexample @c ada 3360 type DT is new Root with record 3361 C_Value : Natural := 2009; 3362 end record; 3363@end smallexample 3364 3365In this case the components DT inherited from the C++ side must be 3366initialized by a C++ constructor, and the additional Ada components 3367of type DT are initialized by GNAT. The initialization of such an 3368object is done either by default, or by means of a function returning 3369an aggregate of type DT, or by means of an extension aggregate. 3370 3371@smallexample @c ada 3372 Obj5 : DT; 3373 Obj6 : DT := Function_Returning_DT (50); 3374 Obj7 : DT := (Constructor (30,40) with C_Value => 50); 3375@end smallexample 3376 3377The declaration of @code{Obj5} invokes the default constructors: the 3378C++ default constructor of the parent type takes care of the initialization 3379of the components inherited from Root, and GNAT takes care of the default 3380initialization of the additional Ada components of type DT (that is, 3381@code{C_Value} is initialized to value 2009). The order of invocation of 3382the constructors is consistent with the order of elaboration required by 3383Ada and C++. That is, the constructor of the parent type is always called 3384before the constructor of the derived type. 3385 3386Let us now consider a record that has components whose type is imported 3387from C++. For example: 3388 3389@smallexample @c ada 3390 type Rec1 is limited record 3391 Data1 : Root := Constructor (10); 3392 Value : Natural := 1000; 3393 end record; 3394 3395 type Rec2 (D : Integer := 20) is limited record 3396 Rec : Rec1; 3397 Data2 : Root := Constructor (D, 30); 3398 end record; 3399@end smallexample 3400 3401The initialization of an object of type @code{Rec2} will call the 3402non-default C++ constructors specified for the imported components. 3403For example: 3404 3405@smallexample @c ada 3406 Obj8 : Rec2 (40); 3407@end smallexample 3408 3409Using Ada 2005 we can use limited aggregates to initialize an object 3410invoking C++ constructors that differ from those specified in the type 3411declarations. For example: 3412 3413@smallexample @c ada 3414 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16), 3415 others => <>), 3416 others => <>); 3417@end smallexample 3418 3419The above declaration uses an Ada 2005 limited aggregate to 3420initialize @code{Obj9}, and the C++ constructor that has two integer 3421arguments is invoked to initialize the @code{Data1} component instead 3422of the constructor specified in the declaration of type @code{Rec1}. In 3423Ada 2005 the box in the aggregate indicates that unspecified components 3424are initialized using the expression (if any) available in the component 3425declaration. That is, in this case discriminant @code{D} is initialized 3426to value @code{20}, @code{Value} is initialized to value 1000, and the 3427non-default C++ constructor that handles two integers takes care of 3428initializing component @code{Data2} with values @code{20,30}. 3429 3430In Ada 2005 we can use the extended return statement to build the Ada 3431equivalent to C++ non-default constructors. For example: 3432 3433@smallexample @c ada 3434 function Constructor (V : Integer) return Rec2 is 3435 begin 3436 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20), 3437 others => <>), 3438 others => <>) do 3439 -- Further actions required for construction of 3440 -- objects of type Rec2 3441 ... 3442 end record; 3443 end Constructor; 3444@end smallexample 3445 3446In this example the extended return statement construct is used to 3447build in place the returned object whose components are initialized 3448by means of a limited aggregate. Any further action associated with 3449the constructor can be placed inside the construct. 3450 3451@node Interfacing with C++ at the Class Level 3452@subsection Interfacing with C++ at the Class Level 3453@noindent 3454In this section we demonstrate the GNAT features for interfacing with 3455C++ by means of an example making use of Ada 2005 abstract interface 3456types. This example consists of a classification of animals; classes 3457have been used to model our main classification of animals, and 3458interfaces provide support for the management of secondary 3459classifications. We first demonstrate a case in which the types and 3460constructors are defined on the C++ side and imported from the Ada 3461side, and latter the reverse case. 3462 3463The root of our derivation will be the @code{Animal} class, with a 3464single private attribute (the @code{Age} of the animal) and two public 3465primitives to set and get the value of this attribute. 3466 3467@smallexample 3468@b{class} Animal @{ 3469 @b{public}: 3470 @b{virtual} void Set_Age (int New_Age); 3471 @b{virtual} int Age (); 3472 @b{private}: 3473 int Age_Count; 3474@}; 3475@end smallexample 3476 3477Abstract interface types are defined in C++ by means of classes with pure 3478virtual functions and no data members. In our example we will use two 3479interfaces that provide support for the common management of @code{Carnivore} 3480and @code{Domestic} animals: 3481 3482@smallexample 3483@b{class} Carnivore @{ 3484@b{public}: 3485 @b{virtual} int Number_Of_Teeth () = 0; 3486@}; 3487 3488@b{class} Domestic @{ 3489@b{public}: 3490 @b{virtual void} Set_Owner (char* Name) = 0; 3491@}; 3492@end smallexample 3493 3494Using these declarations, we can now say that a @code{Dog} is an animal that is 3495both Carnivore and Domestic, that is: 3496 3497@smallexample 3498@b{class} Dog : Animal, Carnivore, Domestic @{ 3499 @b{public}: 3500 @b{virtual} int Number_Of_Teeth (); 3501 @b{virtual} void Set_Owner (char* Name); 3502 3503 Dog(); // Constructor 3504 @b{private}: 3505 int Tooth_Count; 3506 char *Owner; 3507@}; 3508@end smallexample 3509 3510In the following examples we will assume that the previous declarations are 3511located in a file named @code{animals.h}. The following package demonstrates 3512how to import these C++ declarations from the Ada side: 3513 3514@smallexample @c ada 3515with Interfaces.C.Strings; use Interfaces.C.Strings; 3516package Animals is 3517 type Carnivore is interface; 3518 pragma Convention (C_Plus_Plus, Carnivore); 3519 function Number_Of_Teeth (X : Carnivore) 3520 return Natural is abstract; 3521 3522 type Domestic is interface; 3523 pragma Convention (C_Plus_Plus, Set_Owner); 3524 procedure Set_Owner 3525 (X : in out Domestic; 3526 Name : Chars_Ptr) is abstract; 3527 3528 type Animal is tagged record 3529 Age : Natural := 0; 3530 end record; 3531 pragma Import (C_Plus_Plus, Animal); 3532 3533 procedure Set_Age (X : in out Animal; Age : Integer); 3534 pragma Import (C_Plus_Plus, Set_Age); 3535 3536 function Age (X : Animal) return Integer; 3537 pragma Import (C_Plus_Plus, Age); 3538 3539 type Dog is new Animal and Carnivore and Domestic with record 3540 Tooth_Count : Natural; 3541 Owner : String (1 .. 30); 3542 end record; 3543 pragma Import (C_Plus_Plus, Dog); 3544 3545 function Number_Of_Teeth (A : Dog) return Integer; 3546 pragma Import (C_Plus_Plus, Number_Of_Teeth); 3547 3548 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr); 3549 pragma Import (C_Plus_Plus, Set_Owner); 3550 3551 function New_Dog return Dog; 3552 pragma CPP_Constructor (New_Dog); 3553 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev"); 3554end Animals; 3555@end smallexample 3556 3557Thanks to the compatibility between GNAT run-time structures and the C++ ABI, 3558interfacing with these C++ classes is easy. The only requirement is that all 3559the primitives and components must be declared exactly in the same order in 3560the two languages. 3561 3562Regarding the abstract interfaces, we must indicate to the GNAT compiler by 3563means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass 3564the arguments to the called primitives will be the same as for C++. For the 3565imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus} 3566to indicate that they have been defined on the C++ side; this is required 3567because the dispatch table associated with these tagged types will be built 3568in the C++ side and therefore will not contain the predefined Ada primitives 3569which Ada would otherwise expect. 3570 3571As the reader can see there is no need to indicate the C++ mangled names 3572associated with each subprogram because it is assumed that all the calls to 3573these primitives will be dispatching calls. The only exception is the 3574constructor, which must be registered with the compiler by means of 3575@code{pragma CPP_Constructor} and needs to provide its associated C++ 3576mangled name because the Ada compiler generates direct calls to it. 3577 3578With the above packages we can now declare objects of type Dog on the Ada side 3579and dispatch calls to the corresponding subprograms on the C++ side. We can 3580also extend the tagged type Dog with further fields and primitives, and 3581override some of its C++ primitives on the Ada side. For example, here we have 3582a type derivation defined on the Ada side that inherits all the dispatching 3583primitives of the ancestor from the C++ side. 3584 3585@smallexample 3586@b{with} Animals; @b{use} Animals; 3587@b{package} Vaccinated_Animals @b{is} 3588 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record}; 3589 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean; 3590@b{end} Vaccinated_Animals; 3591@end smallexample 3592 3593It is important to note that, because of the ABI compatibility, the programmer 3594does not need to add any further information to indicate either the object 3595layout or the dispatch table entry associated with each dispatching operation. 3596 3597Now let us define all the types and constructors on the Ada side and export 3598them to C++, using the same hierarchy of our previous example: 3599 3600@smallexample @c ada 3601with Interfaces.C.Strings; 3602use Interfaces.C.Strings; 3603package Animals is 3604 type Carnivore is interface; 3605 pragma Convention (C_Plus_Plus, Carnivore); 3606 function Number_Of_Teeth (X : Carnivore) 3607 return Natural is abstract; 3608 3609 type Domestic is interface; 3610 pragma Convention (C_Plus_Plus, Set_Owner); 3611 procedure Set_Owner 3612 (X : in out Domestic; 3613 Name : Chars_Ptr) is abstract; 3614 3615 type Animal is tagged record 3616 Age : Natural := 0; 3617 end record; 3618 pragma Convention (C_Plus_Plus, Animal); 3619 3620 procedure Set_Age (X : in out Animal; Age : Integer); 3621 pragma Export (C_Plus_Plus, Set_Age); 3622 3623 function Age (X : Animal) return Integer; 3624 pragma Export (C_Plus_Plus, Age); 3625 3626 type Dog is new Animal and Carnivore and Domestic with record 3627 Tooth_Count : Natural; 3628 Owner : String (1 .. 30); 3629 end record; 3630 pragma Convention (C_Plus_Plus, Dog); 3631 3632 function Number_Of_Teeth (A : Dog) return Integer; 3633 pragma Export (C_Plus_Plus, Number_Of_Teeth); 3634 3635 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr); 3636 pragma Export (C_Plus_Plus, Set_Owner); 3637 3638 function New_Dog return Dog'Class; 3639 pragma Export (C_Plus_Plus, New_Dog); 3640end Animals; 3641@end smallexample 3642 3643Compared with our previous example the only difference is the use of 3644@code{pragma Export} to indicate to the GNAT compiler that the primitives will 3645be available to C++. Thanks to the ABI compatibility, on the C++ side there is 3646nothing else to be done; as explained above, the only requirement is that all 3647the primitives and components are declared in exactly the same order. 3648 3649For completeness, let us see a brief C++ main program that uses the 3650declarations available in @code{animals.h} (presented in our first example) to 3651import and use the declarations from the Ada side, properly initializing and 3652finalizing the Ada run-time system along the way: 3653 3654@smallexample 3655@b{#include} "animals.h" 3656@b{#include} <iostream> 3657@b{using namespace} std; 3658 3659void Check_Carnivore (Carnivore *obj) @{@dots{}@} 3660void Check_Domestic (Domestic *obj) @{@dots{}@} 3661void Check_Animal (Animal *obj) @{@dots{}@} 3662void Check_Dog (Dog *obj) @{@dots{}@} 3663 3664@b{extern} "C" @{ 3665 void adainit (void); 3666 void adafinal (void); 3667 Dog* new_dog (); 3668@} 3669 3670void test () 3671@{ 3672 Dog *obj = new_dog(); // Ada constructor 3673 Check_Carnivore (obj); // Check secondary DT 3674 Check_Domestic (obj); // Check secondary DT 3675 Check_Animal (obj); // Check primary DT 3676 Check_Dog (obj); // Check primary DT 3677@} 3678 3679int main () 3680@{ 3681 adainit (); test(); adafinal (); 3682 return 0; 3683@} 3684@end smallexample 3685 3686@node Comparison between GNAT and C/C++ Compilation Models 3687@section Comparison between GNAT and C/C++ Compilation Models 3688 3689@noindent 3690The GNAT model of compilation is close to the C and C++ models. You can 3691think of Ada specs as corresponding to header files in C. As in C, you 3692don't need to compile specs; they are compiled when they are used. The 3693Ada @code{with} is similar in effect to the @code{#include} of a C 3694header. 3695 3696One notable difference is that, in Ada, you may compile specs separately 3697to check them for semantic and syntactic accuracy. This is not always 3698possible with C headers because they are fragments of programs that have 3699less specific syntactic or semantic rules. 3700 3701The other major difference is the requirement for running the binder, 3702which performs two important functions. First, it checks for 3703consistency. In C or C++, the only defense against assembling 3704inconsistent programs lies outside the compiler, in a makefile, for 3705example. The binder satisfies the Ada requirement that it be impossible 3706to construct an inconsistent program when the compiler is used in normal 3707mode. 3708 3709@cindex Elaboration order control 3710The other important function of the binder is to deal with elaboration 3711issues. There are also elaboration issues in C++ that are handled 3712automatically. This automatic handling has the advantage of being 3713simpler to use, but the C++ programmer has no control over elaboration. 3714Where @code{gnatbind} might complain there was no valid order of 3715elaboration, a C++ compiler would simply construct a program that 3716malfunctioned at run time. 3717@end ifclear 3718 3719@node Comparison between GNAT and Conventional Ada Library Models 3720@section Comparison between GNAT and Conventional Ada Library Models 3721 3722@noindent 3723This section is intended for Ada programmers who have 3724used an Ada compiler implementing the traditional Ada library 3725model, as described in the Ada Reference Manual. 3726 3727@cindex GNAT library 3728In GNAT, there is no ``library'' in the normal sense. Instead, the set of 3729source files themselves acts as the library. Compiling Ada programs does 3730not generate any centralized information, but rather an object file and 3731a ALI file, which are of interest only to the binder and linker. 3732In a traditional system, the compiler reads information not only from 3733the source file being compiled, but also from the centralized library. 3734This means that the effect of a compilation depends on what has been 3735previously compiled. In particular: 3736 3737@itemize @bullet 3738@item 3739When a unit is @code{with}'ed, the unit seen by the compiler corresponds 3740to the version of the unit most recently compiled into the library. 3741 3742@item 3743Inlining is effective only if the necessary body has already been 3744compiled into the library. 3745 3746@item 3747Compiling a unit may obsolete other units in the library. 3748@end itemize 3749 3750@noindent 3751In GNAT, compiling one unit never affects the compilation of any other 3752units because the compiler reads only source files. Only changes to source 3753files can affect the results of a compilation. In particular: 3754 3755@itemize @bullet 3756@item 3757When a unit is @code{with}'ed, the unit seen by the compiler corresponds 3758to the source version of the unit that is currently accessible to the 3759compiler. 3760 3761@item 3762@cindex Inlining 3763Inlining requires the appropriate source files for the package or 3764subprogram bodies to be available to the compiler. Inlining is always 3765effective, independent of the order in which units are complied. 3766 3767@item 3768Compiling a unit never affects any other compilations. The editing of 3769sources may cause previous compilations to be out of date if they 3770depended on the source file being modified. 3771@end itemize 3772 3773@noindent 3774The most important result of these differences is that order of compilation 3775is never significant in GNAT. There is no situation in which one is 3776required to do one compilation before another. What shows up as order of 3777compilation requirements in the traditional Ada library becomes, in 3778GNAT, simple source dependencies; in other words, there is only a set 3779of rules saying what source files must be present when a file is 3780compiled. 3781 3782@ifset vms 3783@node Placement of temporary files 3784@section Placement of temporary files 3785@cindex Temporary files (user control over placement) 3786 3787@noindent 3788GNAT creates temporary files in the directory designated by the environment 3789variable @env{TMPDIR}. 3790(See the HP @emph{C RTL Reference Manual} on the function @code{getenv()} 3791for detailed information on how environment variables are resolved. 3792For most users the easiest way to make use of this feature is to simply 3793define @env{TMPDIR} as a job level logical name). 3794For example, if you wish to use a Ramdisk (assuming DECRAM is installed) 3795for compiler temporary files, then you can include something like the 3796following command in your @file{LOGIN.COM} file: 3797 3798@smallexample 3799$ define/job TMPDIR "/disk$scratchram/000000/temp/" 3800@end smallexample 3801 3802@noindent 3803If @env{TMPDIR} is not defined, then GNAT uses the directory designated by 3804@env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory 3805designated by @env{TEMP}. 3806If none of these environment variables are defined then GNAT uses the 3807directory designated by the logical name @code{SYS$SCRATCH:} 3808(by default the user's home directory). If all else fails 3809GNAT uses the current directory for temporary files. 3810@end ifset 3811 3812@c ************************* 3813@node Compiling Using gcc 3814@chapter Compiling Using @command{gcc} 3815 3816@noindent 3817This chapter discusses how to compile Ada programs using the @command{gcc} 3818command. It also describes the set of switches 3819that can be used to control the behavior of the compiler. 3820@menu 3821* Compiling Programs:: 3822* Switches for gcc:: 3823* Search Paths and the Run-Time Library (RTL):: 3824* Order of Compilation Issues:: 3825* Examples:: 3826@end menu 3827 3828@node Compiling Programs 3829@section Compiling Programs 3830 3831@noindent 3832The first step in creating an executable program is to compile the units 3833of the program using the @command{gcc} command. You must compile the 3834following files: 3835 3836@itemize @bullet 3837@item 3838the body file (@file{.adb}) for a library level subprogram or generic 3839subprogram 3840 3841@item 3842the spec file (@file{.ads}) for a library level package or generic 3843package that has no body 3844 3845@item 3846the body file (@file{.adb}) for a library level package 3847or generic package that has a body 3848 3849@end itemize 3850 3851@noindent 3852You need @emph{not} compile the following files 3853 3854@itemize @bullet 3855 3856@item 3857the spec of a library unit which has a body 3858 3859@item 3860subunits 3861@end itemize 3862 3863@noindent 3864because they are compiled as part of compiling related units. GNAT 3865package specs 3866when the corresponding body is compiled, and subunits when the parent is 3867compiled. 3868 3869@cindex cannot generate code 3870If you attempt to compile any of these files, you will get one of the 3871following error messages (where @var{fff} is the name of the file you 3872compiled): 3873 3874@smallexample 3875cannot generate code for file @var{fff} (package spec) 3876to check package spec, use -gnatc 3877 3878cannot generate code for file @var{fff} (missing subunits) 3879to check parent unit, use -gnatc 3880 3881cannot generate code for file @var{fff} (subprogram spec) 3882to check subprogram spec, use -gnatc 3883 3884cannot generate code for file @var{fff} (subunit) 3885to check subunit, use -gnatc 3886@end smallexample 3887 3888@noindent 3889As indicated by the above error messages, if you want to submit 3890one of these files to the compiler to check for correct semantics 3891without generating code, then use the @option{-gnatc} switch. 3892 3893The basic command for compiling a file containing an Ada unit is 3894 3895@smallexample 3896@c $ gcc -c @ovar{switches} @file{file name} 3897@c Expanding @ovar macro inline (explanation in macro def comments) 3898$ gcc -c @r{[}@var{switches}@r{]} @file{file name} 3899@end smallexample 3900 3901@noindent 3902where @var{file name} is the name of the Ada file (usually 3903having an extension 3904@file{.ads} for a spec or @file{.adb} for a body). 3905@ifclear vms 3906You specify the 3907@option{-c} switch to tell @command{gcc} to compile, but not link, the file. 3908@end ifclear 3909The result of a successful compilation is an object file, which has the 3910same name as the source file but an extension of @file{.o} and an Ada 3911Library Information (ALI) file, which also has the same name as the 3912source file, but with @file{.ali} as the extension. GNAT creates these 3913two output files in the current directory, but you may specify a source 3914file in any directory using an absolute or relative path specification 3915containing the directory information. 3916 3917@findex gnat1 3918@command{gcc} is actually a driver program that looks at the extensions of 3919the file arguments and loads the appropriate compiler. For example, the 3920GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}. 3921These programs are in directories known to the driver program (in some 3922configurations via environment variables you set), but need not be in 3923your path. The @command{gcc} driver also calls the assembler and any other 3924utilities needed to complete the generation of the required object 3925files. 3926 3927It is possible to supply several file names on the same @command{gcc} 3928command. This causes @command{gcc} to call the appropriate compiler for 3929each file. For example, the following command lists three separate 3930files to be compiled: 3931 3932@smallexample 3933$ gcc -c x.adb y.adb z.c 3934@end smallexample 3935 3936@noindent 3937calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and 3938@file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}. 3939The compiler generates three object files @file{x.o}, @file{y.o} and 3940@file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the 3941Ada compilations. Any switches apply to all the files ^listed,^listed.^ 3942@ifclear vms 3943except for 3944@option{-gnat@var{x}} switches, which apply only to Ada compilations. 3945@end ifclear 3946 3947@node Switches for gcc 3948@section Switches for @command{gcc} 3949 3950@noindent 3951The @command{gcc} command accepts switches that control the 3952compilation process. These switches are fully described in this section. 3953First we briefly list all the switches, in alphabetical order, then we 3954describe the switches in more detail in functionally grouped sections. 3955 3956More switches exist for GCC than those documented here, especially 3957for specific targets. However, their use is not recommended as 3958they may change code generation in ways that are incompatible with 3959the Ada run-time library, or can cause inconsistencies between 3960compilation units. 3961 3962@menu 3963* Output and Error Message Control:: 3964* Warning Message Control:: 3965* Debugging and Assertion Control:: 3966* Validity Checking:: 3967* Style Checking:: 3968* Run-Time Checks:: 3969* Using gcc for Syntax Checking:: 3970* Using gcc for Semantic Checking:: 3971* Compiling Different Versions of Ada:: 3972* Character Set Control:: 3973* File Naming Control:: 3974* Subprogram Inlining Control:: 3975* Auxiliary Output Control:: 3976* Debugging Control:: 3977* Exception Handling Control:: 3978* Units to Sources Mapping Files:: 3979* Integrated Preprocessing:: 3980* Code Generation Control:: 3981@ifset vms 3982* Return Codes:: 3983@end ifset 3984@end menu 3985 3986@table @option 3987@c !sort! 3988@ifclear vms 3989@cindex @option{-b} (@command{gcc}) 3990@item -b @var{target} 3991Compile your program to run on @var{target}, which is the name of a 3992system configuration. You must have a GNAT cross-compiler built if 3993@var{target} is not the same as your host system. 3994 3995@item -B@var{dir} 3996@cindex @option{-B} (@command{gcc}) 3997Load compiler executables (for example, @code{gnat1}, the Ada compiler) 3998from @var{dir} instead of the default location. Only use this switch 3999when multiple versions of the GNAT compiler are available. 4000@xref{Directory Options,, Options for Directory Search, gcc, Using the 4001GNU Compiler Collection (GCC)}, for further details. You would normally 4002use the @option{-b} or @option{-V} switch instead. 4003 4004@item -c 4005@cindex @option{-c} (@command{gcc}) 4006Compile. Always use this switch when compiling Ada programs. 4007 4008Note: for some other languages when using @command{gcc}, notably in 4009the case of C and C++, it is possible to use 4010use @command{gcc} without a @option{-c} switch to 4011compile and link in one step. In the case of GNAT, you 4012cannot use this approach, because the binder must be run 4013and @command{gcc} cannot be used to run the GNAT binder. 4014@end ifclear 4015 4016@item -fcallgraph-info@r{[}=su,da@r{]} 4017@cindex @option{-fcallgraph-info} (@command{gcc}) 4018Makes the compiler output callgraph information for the program, on a 4019per-file basis. The information is generated in the VCG format. It can 4020be decorated with additional, per-node and/or per-edge information, if a 4021list of comma-separated markers is additionally specified. When the 4022@var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da} 4023marker is specified, the callgraph is decorated with information about 4024dynamically allocated objects. 4025 4026@item -fdump-scos 4027@cindex @option{-fdump-scos} (@command{gcc}) 4028Generates SCO (Source Coverage Obligation) information in the ALI file. 4029This information is used by advanced coverage tools. See unit @file{SCOs} 4030in the compiler sources for details in files @file{scos.ads} and 4031@file{scos.adb}. 4032 4033@item -flto@r{[}=n@r{]} 4034@cindex @option{-flto} (@command{gcc}) 4035Enables Link Time Optimization. This switch must be used in conjunction 4036with the traditional @option{-Ox} switches and instructs the compiler to 4037defer most optimizations until the link stage. The advantage of this 4038approach is that the compiler can do a whole-program analysis and choose 4039the best interprocedural optimization strategy based on a complete view 4040of the program, instead of a fragmentary view with the usual approach. 4041This can also speed up the compilation of huge programs and reduce the 4042size of the final executable, compared with a per-unit compilation with 4043full inlining across modules enabled with the @option{-gnatn2} switch. 4044The drawback of this approach is that it may require much more memory. 4045The switch, as well as the accompanying @option{-Ox} switches, must be 4046specified both for the compilation and the link phases. 4047If the @var{n} parameter is specified, the optimization and final code 4048generation at link time are executed using @var{n} parallel jobs by 4049means of an installed @command{make} program. 4050 4051@item -fno-inline 4052@cindex @option{-fno-inline} (@command{gcc}) 4053Suppresses all inlining, even if other optimization or inlining 4054switches are set. This includes suppression of inlining that 4055results from the use of the pragma @code{Inline_Always}. 4056Any occurrences of pragma @code{Inline} or @code{Inline_Always} 4057are ignored, and @option{-gnatn} and @option{-gnatN} have no 4058effects if this switch is present. Note that inlining can also 4059be suppressed on a finer-grained basis with pragma @code{No_Inline}. 4060 4061@item -fno-inline-functions 4062@cindex @option{-fno-inline-functions} (@command{gcc}) 4063Suppresses automatic inlining of subprograms, which is enabled 4064if @option{-O3} is used. 4065 4066@item -fno-inline-small-functions 4067@cindex @option{-fno-inline-small-functions} (@command{gcc}) 4068Suppresses automatic inlining of small subprograms, which is enabled 4069if @option{-O2} is used. 4070 4071@item -fno-inline-functions-called-once 4072@cindex @option{-fno-inline-functions-called-once} (@command{gcc}) 4073Suppresses inlining of subprograms local to the unit and called once 4074from within it, which is enabled if @option{-O1} is used. 4075 4076@item -fno-ivopts 4077@cindex @option{-fno-ivopts} (@command{gcc}) 4078Suppresses high-level loop induction variable optimizations, which are 4079enabled if @option{-O1} is used. These optimizations are generally 4080profitable but, for some specific cases of loops with numerous uses 4081of the iteration variable that follow a common pattern, they may end 4082up destroying the regularity that could be exploited at a lower level 4083and thus producing inferior code. 4084 4085@item -fno-strict-aliasing 4086@cindex @option{-fno-strict-aliasing} (@command{gcc}) 4087Causes the compiler to avoid assumptions regarding non-aliasing 4088of objects of different types. See 4089@ref{Optimization and Strict Aliasing} for details. 4090 4091@item -fstack-check 4092@cindex @option{-fstack-check} (@command{gcc}) 4093Activates stack checking. 4094See @ref{Stack Overflow Checking} for details. 4095 4096@item -fstack-usage 4097@cindex @option{-fstack-usage} (@command{gcc}) 4098Makes the compiler output stack usage information for the program, on a 4099per-subprogram basis. See @ref{Static Stack Usage Analysis} for details. 4100 4101@item ^-g^/DEBUG^ 4102@cindex @option{^-g^/DEBUG^} (@command{gcc}) 4103Generate debugging information. This information is stored in the object 4104file and copied from there to the final executable file by the linker, 4105where it can be read by the debugger. You must use the 4106@option{^-g^/DEBUG^} switch if you plan on using the debugger. 4107 4108@item -gnat83 4109@cindex @option{-gnat83} (@command{gcc}) 4110Enforce Ada 83 restrictions. 4111 4112@item -gnat95 4113@cindex @option{-gnat95} (@command{gcc}) 4114Enforce Ada 95 restrictions. 4115 4116@item -gnat05 4117@cindex @option{-gnat05} (@command{gcc}) 4118Allow full Ada 2005 features. 4119 4120@item -gnat2005 4121@cindex @option{-gnat2005} (@command{gcc}) 4122Allow full Ada 2005 features (same as @option{-gnat05}) 4123 4124@item -gnat12 4125@cindex @option{-gnat12} (@command{gcc}) 4126 4127@item -gnat2012 4128@cindex @option{-gnat2012} (@command{gcc}) 4129Allow full Ada 2012 features (same as @option{-gnat12}) 4130 4131@item -gnata 4132@cindex @option{-gnata} (@command{gcc}) 4133Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be 4134activated. Note that these pragmas can also be controlled using the 4135configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}. 4136It also activates pragmas @code{Check}, @code{Precondition}, and 4137@code{Postcondition}. Note that these pragmas can also be controlled 4138using the configuration pragma @code{Check_Policy}. In Ada 2012, it 4139also activates all assertions defined in the RM as aspects: preconditions, 4140postconditions, type invariants and (sub)type predicates. In all Ada modes, 4141corresponding pragmas for type invariants and (sub)type predicates are 4142also activated. 4143 4144@item -gnatA 4145@cindex @option{-gnatA} (@command{gcc}) 4146Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present, 4147it will be ignored. 4148 4149@item -gnatb 4150@cindex @option{-gnatb} (@command{gcc}) 4151Generate brief messages to @file{stderr} even if verbose mode set. 4152 4153@item -gnatB 4154@cindex @option{-gnatB} (@command{gcc}) 4155Assume no invalid (bad) values except for 'Valid attribute use 4156(@pxref{Validity Checking}). 4157 4158@item -gnatc 4159@cindex @option{-gnatc} (@command{gcc}) 4160Check syntax and semantics only (no code generation attempted). 4161 4162@item -gnatC 4163@cindex @option{-gnatC} (@command{gcc}) 4164Generate CodePeer information (no code generation attempted). 4165This switch will generate an intermediate representation suitable for 4166use by CodePeer (@file{.scil} files). This switch is not compatible with 4167code generation (it will, among other things, disable some switches such 4168as -gnatn, and enable others such as -gnata). 4169 4170@item -gnatd 4171@cindex @option{-gnatd} (@command{gcc}) 4172Specify debug options for the compiler. The string of characters after 4173the @option{-gnatd} specify the specific debug options. The possible 4174characters are 0-9, a-z, A-Z, optionally preceded by a dot. See 4175compiler source file @file{debug.adb} for details of the implemented 4176debug options. Certain debug options are relevant to applications 4177programmers, and these are documented at appropriate points in this 4178users guide. 4179 4180@ifclear vms 4181@item -gnatD 4182@cindex @option{-gnatD[nn]} (@command{gcc}) 4183@end ifclear 4184@ifset vms 4185@item /XDEBUG /LXDEBUG=nnn 4186@end ifset 4187Create expanded source files for source level debugging. This switch 4188also suppress generation of cross-reference information 4189(see @option{-gnatx}). 4190 4191@item ^-gnateA^/ALIASING_CHECK^ 4192@cindex @option{-gnateA} (@command{gcc}) 4193Check that there is no aliasing between two parameters of the same subprogram. 4194 4195@item -gnatec=@var{path} 4196@cindex @option{-gnatec} (@command{gcc}) 4197Specify a configuration pragma file 4198@ifclear vms 4199(the equal sign is optional) 4200@end ifclear 4201(@pxref{The Configuration Pragmas Files}). 4202 4203@item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^ 4204@cindex @option{-gnated} (@command{gcc}) 4205Disable atomic synchronization 4206 4207@item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]} 4208@cindex @option{-gnateD} (@command{gcc}) 4209Defines a symbol, associated with @var{value}, for preprocessing. 4210(@pxref{Integrated Preprocessing}). 4211 4212@item -gnateE 4213@cindex @option{-gnateE} (@command{gcc}) 4214Generate extra information in exception messages. In particular, display 4215extra column information and the value and range associated with index and 4216range check failures, and extra column information for access checks. 4217In cases where the compiler is able to determine at compile time that 4218a check will fail, it gives a warning, and the extra information is not 4219produced at run time. 4220 4221@item -gnatef 4222@cindex @option{-gnatef} (@command{gcc}) 4223Display full source path name in brief error messages. 4224 4225@item -gnateF 4226@cindex @option{-gnateF} (@command{gcc}) 4227Check for overflow on all floating-point operations, including those 4228for unconstrained predefined types. See description of pragma 4229@code{Check_Float_Overflow} in GNAT RM. 4230 4231@item -gnateG 4232@cindex @option{-gnateG} (@command{gcc}) 4233Save result of preprocessing in a text file. 4234 4235@item -gnatei@var{nnn} 4236@cindex @option{-gnatei} (@command{gcc}) 4237Set maximum number of instantiations during compilation of a single unit to 4238@var{nnn}. This may be useful in increasing the default maximum of 8000 for 4239the rare case when a single unit legitimately exceeds this limit. 4240 4241@item -gnateI@var{nnn} 4242@cindex @option{-gnateI} (@command{gcc}) 4243Indicates that the source is a multi-unit source and that the index of the 4244unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need 4245to be a valid index in the multi-unit source. 4246 4247@item -gnatem=@var{path} 4248@cindex @option{-gnatem} (@command{gcc}) 4249Specify a mapping file 4250@ifclear vms 4251(the equal sign is optional) 4252@end ifclear 4253(@pxref{Units to Sources Mapping Files}). 4254 4255@item -gnatep=@var{file} 4256@cindex @option{-gnatep} (@command{gcc}) 4257Specify a preprocessing data file 4258@ifclear vms 4259(the equal sign is optional) 4260@end ifclear 4261(@pxref{Integrated Preprocessing}). 4262 4263@item -gnateP 4264@cindex @option{-gnateP} (@command{gcc}) 4265Turn categorization dependency errors into warnings. 4266Ada requires that units that WITH one another have compatible categories, for 4267example a Pure unit cannot WITH a Preelaborate unit. If this switch is used, 4268these errors become warnings (which can be ignored, or suppressed in the usual 4269manner). This can be useful in some specialized circumstances such as the 4270temporary use of special test software. 4271 4272@item -gnateS 4273@cindex @option{-gnateS} (@command{gcc}) 4274Synonym of @option{-fdump-scos}, kept for backards compatibility. 4275 4276@item ^-gnatet^/TARGET_DEPENDENT_INFO^ 4277@cindex @option{-gnatet} (@command{gcc}) 4278Generate target dependent information. 4279 4280@item ^-gnateV^/PARAMETER_VALIDITY_CHECK^ 4281@cindex @option{-gnateV} (@command{gcc}) 4282Check validity of subprogram parameters. 4283 4284@item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^ 4285@cindex @option{-gnateY} (@command{gcc}) 4286Ignore all STYLE_CHECKS pragmas. Full legality checks 4287are still carried out, but the pragmas have no effect 4288on what style checks are active. This allows all style 4289checking options to be controlled from the command line. 4290 4291@item -gnatE 4292@cindex @option{-gnatE} (@command{gcc}) 4293Full dynamic elaboration checks. 4294 4295@item -gnatf 4296@cindex @option{-gnatf} (@command{gcc}) 4297Full errors. Multiple errors per line, all undefined references, do not 4298attempt to suppress cascaded errors. 4299 4300@item -gnatF 4301@cindex @option{-gnatF} (@command{gcc}) 4302Externals names are folded to all uppercase. 4303 4304@item ^-gnatg^/GNAT_INTERNAL^ 4305@cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc}) 4306Internal GNAT implementation mode. This should not be used for 4307applications programs, it is intended only for use by the compiler 4308and its run-time library. For documentation, see the GNAT sources. 4309Note that @option{^-gnatg^/GNAT_INTERNAL^} implies 4310@option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and 4311@option{^-gnatyg^/STYLE_CHECKS=GNAT^} 4312so that all standard warnings and all standard style options are turned on. 4313All warnings and style messages are treated as errors. 4314 4315@ifclear vms 4316@item -gnatG=nn 4317@cindex @option{-gnatG[nn]} (@command{gcc}) 4318@end ifclear 4319@ifset vms 4320@item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn 4321@end ifset 4322List generated expanded code in source form. 4323 4324@item ^-gnath^/HELP^ 4325@cindex @option{^-gnath^/HELP^} (@command{gcc}) 4326Output usage information. The output is written to @file{stdout}. 4327 4328@item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} 4329@cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc}) 4330Identifier character set 4331@ifclear vms 4332(@var{c}=1/2/3/4/8/9/p/f/n/w). 4333@end ifclear 4334For details of the possible selections for @var{c}, 4335see @ref{Character Set Control}. 4336 4337@item ^-gnatI^/IGNORE_REP_CLAUSES^ 4338@cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc}) 4339Ignore representation clauses. When this switch is used, 4340representation clauses are treated as comments. This is useful 4341when initially porting code where you want to ignore rep clause 4342problems, and also for compiling foreign code (particularly 4343for use with ASIS). The representation clauses that are ignored 4344are: enumeration_representation_clause, record_representation_clause, 4345and attribute_definition_clause for the following attributes: 4346Address, Alignment, Bit_Order, Component_Size, Machine_Radix, 4347Object_Size, Size, Small, Stream_Size, and Value_Size. 4348Note that this option should be used only for compiling -- the 4349code is likely to malfunction at run time. 4350 4351@item -gnatjnn 4352@cindex @option{-gnatjnn} (@command{gcc}) 4353Reformat error messages to fit on nn character lines 4354 4355@item -gnatk=@var{n} 4356@cindex @option{-gnatk} (@command{gcc}) 4357Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^. 4358 4359@item -gnatl 4360@cindex @option{-gnatl} (@command{gcc}) 4361Output full source listing with embedded error messages. 4362 4363@item -gnatL 4364@cindex @option{-gnatL} (@command{gcc}) 4365Used in conjunction with -gnatG or -gnatD to intersperse original 4366source lines (as comment lines with line numbers) in the expanded 4367source output. 4368 4369@item -gnatm=@var{n} 4370@cindex @option{-gnatm} (@command{gcc}) 4371Limit number of detected error or warning messages to @var{n} 4372where @var{n} is in the range 1..999999. The default setting if 4373no switch is given is 9999. If the number of warnings reaches this 4374limit, then a message is output and further warnings are suppressed, 4375but the compilation is continued. If the number of error messages 4376reaches this limit, then a message is output and the compilation 4377is abandoned. The equal sign here is optional. A value of zero 4378means that no limit applies. 4379 4380@item -gnatn[12] 4381@cindex @option{-gnatn} (@command{gcc}) 4382Activate inlining for subprograms for which pragma @code{Inline} is 4383specified. This inlining is performed by the GCC back-end. An optional 4384digit sets the inlining level: 1 for moderate inlining across modules 4385or 2 for full inlining across modules. If no inlining level is specified, 4386the compiler will pick it based on the optimization level. 4387 4388@item -gnatN 4389@cindex @option{-gnatN} (@command{gcc}) 4390Activate front end inlining for subprograms for which 4391pragma @code{Inline} is specified. This inlining is performed 4392by the front end and will be visible in the 4393@option{-gnatG} output. 4394 4395When using a gcc-based back end (in practice this means using any version 4396of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of 4397@option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred. 4398Historically front end inlining was more extensive than the gcc back end 4399inlining, but that is no longer the case. 4400 4401@item -gnato?? 4402@cindex @option{-gnato??} (@command{gcc}) 4403Set default mode for handling generation of code to avoid intermediate 4404arithmetic overflow. Here `@code{??}' is two digits, a 4405single digit, or nothing. Each digit is one of the digits `@code{1}' 4406through `@code{3}': 4407 4408@itemize @bullet 4409@item @code{1}: 4410all intermediate overflows checked against base type (@code{STRICT}) 4411@item @code{2}: 4412minimize intermediate overflows (@code{MINIMIZED}) 4413@item @code{3}: 4414eliminate intermediate overflows (@code{ELIMINATED}) 4415@end itemize 4416 4417If only one digit appears then it applies to all 4418cases; if two digits are given, then the first applies outside 4419assertions, and the second within assertions. 4420 4421If no digits follow the @option{-gnato}, then it is equivalent to 4422@option{-gnato11}, 4423causing all intermediate overflows to be handled in strict mode. 4424 4425This switch also causes arithmetic overflow checking to be performed 4426(as though pragma @code{Unsuppress (Overflow_Mode)} has been specified. 4427 4428The default if no option @option{-gnato} is given is that overflow handling 4429is in @code{STRICT} mode (computations done using the base type), and that 4430overflow checking is suppressed. 4431 4432Note that division by zero is a separate check that is not 4433controlled by this switch (division by zero checking is on by default). 4434 4435See also @ref{Specifying the Desired Mode}. 4436 4437@item -gnatp 4438@cindex @option{-gnatp} (@command{gcc}) 4439Suppress all checks. See @ref{Run-Time Checks} for details. This switch 4440has no effect if cancelled by a subsequent @option{-gnat-p} switch. 4441 4442@item -gnat-p 4443@cindex @option{-gnat-p} (@command{gcc}) 4444Cancel effect of previous @option{-gnatp} switch. 4445 4446@item -gnatP 4447@cindex @option{-gnatP} (@command{gcc}) 4448Enable polling. This is required on some systems (notably Windows NT) to 4449obtain asynchronous abort and asynchronous transfer of control capability. 4450@xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full 4451details. 4452 4453@item -gnatq 4454@cindex @option{-gnatq} (@command{gcc}) 4455Don't quit. Try semantics, even if parse errors. 4456 4457@item -gnatQ 4458@cindex @option{-gnatQ} (@command{gcc}) 4459Don't quit. Generate @file{ALI} and tree files even if illegalities. 4460 4461@item -gnatr 4462@cindex @option{-gnatr} (@command{gcc}) 4463Treat pragma Restrictions as Restriction_Warnings. 4464 4465@item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^ 4466@cindex @option{-gnatR} (@command{gcc}) 4467Output representation information for declared types and objects. 4468 4469@item -gnats 4470@cindex @option{-gnats} (@command{gcc}) 4471Syntax check only. 4472 4473@item -gnatS 4474@cindex @option{-gnatS} (@command{gcc}) 4475Print package Standard. 4476 4477@item -gnatt 4478@cindex @option{-gnatt} (@command{gcc}) 4479Generate tree output file. 4480 4481@item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn} 4482@cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc}) 4483All compiler tables start at @var{nnn} times usual starting size. 4484 4485@item -gnatu 4486@cindex @option{-gnatu} (@command{gcc}) 4487List units for this compilation. 4488 4489@item -gnatU 4490@cindex @option{-gnatU} (@command{gcc}) 4491Tag all error messages with the unique string ``error:'' 4492 4493@item -gnatv 4494@cindex @option{-gnatv} (@command{gcc}) 4495Verbose mode. Full error output with source lines to @file{stdout}. 4496 4497@item -gnatV 4498@cindex @option{-gnatV} (@command{gcc}) 4499Control level of validity checking (@pxref{Validity Checking}). 4500 4501@item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^ 4502@cindex @option{^-gnatw^/WARNINGS^} (@command{gcc}) 4503Warning mode where 4504^@var{xxx} is a string of option letters that^the list of options^ denotes 4505the exact warnings that 4506are enabled or disabled (@pxref{Warning Message Control}). 4507 4508@item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} 4509@cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc}) 4510Wide character encoding method 4511@ifclear vms 4512(@var{e}=n/h/u/s/e/8). 4513@end ifclear 4514@ifset vms 4515(@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8}) 4516@end ifset 4517 4518@item -gnatx 4519@cindex @option{-gnatx} (@command{gcc}) 4520Suppress generation of cross-reference information. 4521 4522@item -gnatX 4523@cindex @option{-gnatX} (@command{gcc}) 4524Enable GNAT implementation extensions and latest Ada version. 4525 4526@item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^ 4527@cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc}) 4528Enable built-in style checks (@pxref{Style Checking}). 4529 4530@item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m} 4531@cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc}) 4532Distribution stub generation and compilation 4533@ifclear vms 4534(@var{m}=r/c for receiver/caller stubs). 4535@end ifclear 4536@ifset vms 4537(@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs 4538to be generated and compiled). 4539@end ifset 4540 4541@item ^-I^/SEARCH=^@var{dir} 4542@cindex @option{^-I^/SEARCH^} (@command{gcc}) 4543@cindex RTL 4544Direct GNAT to search the @var{dir} directory for source files needed by 4545the current compilation 4546(@pxref{Search Paths and the Run-Time Library (RTL)}). 4547 4548@item ^-I-^/NOCURRENT_DIRECTORY^ 4549@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc}) 4550@cindex RTL 4551Except for the source file named in the command line, do not look for source 4552files in the directory containing the source file named in the command line 4553(@pxref{Search Paths and the Run-Time Library (RTL)}). 4554 4555@ifclear vms 4556@item -mbig-switch 4557@cindex @option{-mbig-switch} (@command{gcc}) 4558@cindex @code{case} statement (effect of @option{-mbig-switch} option) 4559This standard gcc switch causes the compiler to use larger offsets in its 4560jump table representation for @code{case} statements. 4561This may result in less efficient code, but is sometimes necessary 4562(for example on HP-UX targets) 4563@cindex HP-UX and @option{-mbig-switch} option 4564in order to compile large and/or nested @code{case} statements. 4565 4566@item -o @var{file} 4567@cindex @option{-o} (@command{gcc}) 4568This switch is used in @command{gcc} to redirect the generated object file 4569and its associated ALI file. Beware of this switch with GNAT, because it may 4570cause the object file and ALI file to have different names which in turn 4571may confuse the binder and the linker. 4572@end ifclear 4573 4574@item -nostdinc 4575@cindex @option{-nostdinc} (@command{gcc}) 4576Inhibit the search of the default location for the GNAT Run Time 4577Library (RTL) source files. 4578 4579@item -nostdlib 4580@cindex @option{-nostdlib} (@command{gcc}) 4581Inhibit the search of the default location for the GNAT Run Time 4582Library (RTL) ALI files. 4583 4584@ifclear vms 4585@c @item -O@ovar{n} 4586@c Expanding @ovar macro inline (explanation in macro def comments) 4587@item -O@r{[}@var{n}@r{]} 4588@cindex @option{-O} (@command{gcc}) 4589@var{n} controls the optimization level. 4590 4591@table @asis 4592@item n = 0 4593No optimization, the default setting if no @option{-O} appears 4594 4595@item n = 1 4596Normal optimization, the default if you specify @option{-O} without 4597an operand. A good compromise between code quality and compilation 4598time. 4599 4600@item n = 2 4601Extensive optimization, may improve execution time, possibly at the cost of 4602substantially increased compilation time. 4603 4604@item n = 3 4605Same as @option{-O2}, and also includes inline expansion for small subprograms 4606in the same unit. 4607 4608@item n = s 4609Optimize space usage 4610@end table 4611 4612@noindent 4613See also @ref{Optimization Levels}. 4614@end ifclear 4615 4616@ifset vms 4617@item /NOOPTIMIZE 4618@cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE}) 4619Equivalent to @option{/OPTIMIZE=NONE}. 4620This is the default behavior in the absence of an @option{/OPTIMIZE} 4621qualifier. 4622 4623@item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]} 4624@cindex @option{/OPTIMIZE} (@code{GNAT COMPILE}) 4625Selects the level of optimization for your program. The supported 4626keywords are as follows: 4627@table @code 4628@item ALL 4629Perform most optimizations, including those that 4630are expensive. 4631This is the default if the @option{/OPTIMIZE} qualifier is supplied 4632without keyword options. 4633 4634@item NONE 4635Do not do any optimizations. Same as @code{/NOOPTIMIZE}. 4636 4637@item SOME 4638Perform some optimizations, but omit ones that are costly. 4639 4640@item DEVELOPMENT 4641Same as @code{SOME}. 4642 4643@item INLINING 4644Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts 4645automatic inlining of small subprograms within a unit 4646 4647@item UNROLL_LOOPS 4648Try to unroll loops. This keyword may be specified together with 4649any keyword above other than @code{NONE}. Loop unrolling 4650usually, but not always, improves the performance of programs. 4651 4652@item SPACE 4653Optimize space usage 4654@end table 4655 4656@noindent 4657See also @ref{Optimization Levels}. 4658@end ifset 4659 4660@ifclear vms 4661@item -pass-exit-codes 4662@cindex @option{-pass-exit-codes} (@command{gcc}) 4663Catch exit codes from the compiler and use the most meaningful as 4664exit status. 4665@end ifclear 4666 4667@item --RTS=@var{rts-path} 4668@cindex @option{--RTS} (@command{gcc}) 4669Specifies the default location of the runtime library. Same meaning as the 4670equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}). 4671 4672@item ^-S^/ASM^ 4673@cindex @option{^-S^/ASM^} (@command{gcc}) 4674^Used in place of @option{-c} to^Used to^ 4675cause the assembler source file to be 4676generated, using @file{^.s^.S^} as the extension, 4677instead of the object file. 4678This may be useful if you need to examine the generated assembly code. 4679 4680@item ^-fverbose-asm^/VERBOSE_ASM^ 4681@cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc}) 4682^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^ 4683to cause the generated assembly code file to be annotated with variable 4684names, making it significantly easier to follow. 4685 4686@item ^-v^/VERBOSE^ 4687@cindex @option{^-v^/VERBOSE^} (@command{gcc}) 4688Show commands generated by the @command{gcc} driver. Normally used only for 4689debugging purposes or if you need to be sure what version of the 4690compiler you are executing. 4691 4692@ifclear vms 4693@item -V @var{ver} 4694@cindex @option{-V} (@command{gcc}) 4695Execute @var{ver} version of the compiler. This is the @command{gcc} 4696version, not the GNAT version. 4697@end ifclear 4698 4699@item ^-w^/NO_BACK_END_WARNINGS^ 4700@cindex @option{-w} (@command{gcc}) 4701Turn off warnings generated by the back end of the compiler. Use of 4702this switch also causes the default for front end warnings to be set 4703to suppress (as though @option{-gnatws} had appeared at the start of 4704the options). 4705 4706@end table 4707 4708@ifclear vms 4709@c Combining qualifiers does not work on VMS 4710You may combine a sequence of GNAT switches into a single switch. For 4711example, the combined switch 4712 4713@cindex Combining GNAT switches 4714@smallexample 4715-gnatofi3 4716@end smallexample 4717 4718@noindent 4719is equivalent to specifying the following sequence of switches: 4720 4721@smallexample 4722-gnato -gnatf -gnati3 4723@end smallexample 4724@end ifclear 4725 4726@noindent 4727The following restrictions apply to the combination of switches 4728in this manner: 4729 4730@itemize @bullet 4731@item 4732The switch @option{-gnatc} if combined with other switches must come 4733first in the string. 4734 4735@item 4736The switch @option{-gnats} if combined with other switches must come 4737first in the string. 4738 4739@item 4740The switches 4741^^@option{/DISTRIBUTION_STUBS=},^ 4742@option{-gnatzc} and @option{-gnatzr} may not be combined with any other 4743switches, and only one of them may appear in the command line. 4744 4745@item 4746The switch @option{-gnat-p} may not be combined with any other switch. 4747 4748@ifclear vms 4749@item 4750Once a ``y'' appears in the string (that is a use of the @option{-gnaty} 4751switch), then all further characters in the switch are interpreted 4752as style modifiers (see description of @option{-gnaty}). 4753 4754@item 4755Once a ``d'' appears in the string (that is a use of the @option{-gnatd} 4756switch), then all further characters in the switch are interpreted 4757as debug flags (see description of @option{-gnatd}). 4758 4759@item 4760Once a ``w'' appears in the string (that is a use of the @option{-gnatw} 4761switch), then all further characters in the switch are interpreted 4762as warning mode modifiers (see description of @option{-gnatw}). 4763 4764@item 4765Once a ``V'' appears in the string (that is a use of the @option{-gnatV} 4766switch), then all further characters in the switch are interpreted 4767as validity checking options (@pxref{Validity Checking}). 4768 4769@item 4770Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in 4771a combined list of options. 4772@end ifclear 4773@end itemize 4774 4775@node Output and Error Message Control 4776@subsection Output and Error Message Control 4777@findex stderr 4778 4779@noindent 4780The standard default format for error messages is called ``brief format''. 4781Brief format messages are written to @file{stderr} (the standard error 4782file) and have the following form: 4783 4784@smallexample 4785e.adb:3:04: Incorrect spelling of keyword "function" 4786e.adb:4:20: ";" should be "is" 4787@end smallexample 4788 4789@noindent 4790The first integer after the file name is the line number in the file, 4791and the second integer is the column number within the line. 4792@ifclear vms 4793@code{GPS} can parse the error messages 4794and point to the referenced character. 4795@end ifclear 4796The following switches provide control over the error message 4797format: 4798 4799@table @option 4800@c !sort! 4801@item -gnatv 4802@cindex @option{-gnatv} (@command{gcc}) 4803@findex stdout 4804@ifclear vms 4805The v stands for verbose. 4806@end ifclear 4807The effect of this setting is to write long-format error 4808messages to @file{stdout} (the standard output file. 4809The same program compiled with the 4810@option{-gnatv} switch would generate: 4811 4812@smallexample 4813@cartouche 48143. funcion X (Q : Integer) 4815 | 4816>>> Incorrect spelling of keyword "function" 48174. return Integer; 4818 | 4819>>> ";" should be "is" 4820@end cartouche 4821@end smallexample 4822 4823@noindent 4824The vertical bar indicates the location of the error, and the @samp{>>>} 4825prefix can be used to search for error messages. When this switch is 4826used the only source lines output are those with errors. 4827 4828@item -gnatl 4829@cindex @option{-gnatl} (@command{gcc}) 4830@ifclear vms 4831The @code{l} stands for list. 4832@end ifclear 4833This switch causes a full listing of 4834the file to be generated. In the case where a body is 4835compiled, the corresponding spec is also listed, along 4836with any subunits. Typical output from compiling a package 4837body @file{p.adb} might look like: 4838 4839@smallexample @c ada 4840@cartouche 4841 Compiling: p.adb 4842 4843 1. package body p is 4844 2. procedure a; 4845 3. procedure a is separate; 4846 4. begin 4847 5. null 4848 | 4849 >>> missing ";" 4850 4851 6. end; 4852 4853Compiling: p.ads 4854 4855 1. package p is 4856 2. pragma Elaborate_Body 4857 | 4858 >>> missing ";" 4859 4860 3. end p; 4861 4862Compiling: p-a.adb 4863 4864 1. separate p 4865 | 4866 >>> missing "(" 4867 4868 2. procedure a is 4869 3. begin 4870 4. null 4871 | 4872 >>> missing ";" 4873 4874 5. end; 4875@end cartouche 4876@end smallexample 4877 4878@noindent 4879@findex stderr 4880When you specify the @option{-gnatv} or @option{-gnatl} switches and 4881standard output is redirected, a brief summary is written to 4882@file{stderr} (standard error) giving the number of error messages and 4883warning messages generated. 4884 4885@item ^-gnatl^/OUTPUT_FILE^=file 4886@cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc}) 4887This has the same effect as @option{-gnatl} except that the output is 4888written to a file instead of to standard output. If the given name 4889@file{fname} does not start with a period, then it is the full name 4890of the file to be written. If @file{fname} is an extension, it is 4891appended to the name of the file being compiled. For example, if 4892file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst}, 4893then the output is written to file ^xyz.adb.lst^xyz.adb_lst^. 4894 4895@item -gnatU 4896@cindex @option{-gnatU} (@command{gcc}) 4897This switch forces all error messages to be preceded by the unique 4898string ``error:''. This means that error messages take a few more 4899characters in space, but allows easy searching for and identification 4900of error messages. 4901 4902@item -gnatb 4903@cindex @option{-gnatb} (@command{gcc}) 4904@ifclear vms 4905The @code{b} stands for brief. 4906@end ifclear 4907This switch causes GNAT to generate the 4908brief format error messages to @file{stderr} (the standard error 4909file) as well as the verbose 4910format message or full listing (which as usual is written to 4911@file{stdout} (the standard output file). 4912 4913@item -gnatm=@var{n} 4914@cindex @option{-gnatm} (@command{gcc}) 4915@ifclear vms 4916The @code{m} stands for maximum. 4917@end ifclear 4918@var{n} is a decimal integer in the 4919range of 1 to 999999 and limits the number of error or warning 4920messages to be generated. For example, using 4921@option{-gnatm2} might yield 4922 4923@smallexample 4924e.adb:3:04: Incorrect spelling of keyword "function" 4925e.adb:5:35: missing ".." 4926fatal error: maximum number of errors detected 4927compilation abandoned 4928@end smallexample 4929 4930@noindent 4931The default setting if 4932no switch is given is 9999. If the number of warnings reaches this 4933limit, then a message is output and further warnings are suppressed, 4934but the compilation is continued. If the number of error messages 4935reaches this limit, then a message is output and the compilation 4936is abandoned. A value of zero means that no limit applies. 4937 4938@noindent 4939Note that the equal sign is optional, so the switches 4940@option{-gnatm2} and @option{-gnatm=2} are equivalent. 4941 4942@item -gnatf 4943@cindex @option{-gnatf} (@command{gcc}) 4944@cindex Error messages, suppressing 4945@ifclear vms 4946The @code{f} stands for full. 4947@end ifclear 4948Normally, the compiler suppresses error messages that are likely to be 4949redundant. This switch causes all error 4950messages to be generated. In particular, in the case of 4951references to undefined variables. If a given variable is referenced 4952several times, the normal format of messages is 4953@smallexample 4954e.adb:7:07: "V" is undefined (more references follow) 4955@end smallexample 4956 4957@noindent 4958where the parenthetical comment warns that there are additional 4959references to the variable @code{V}. Compiling the same program with the 4960@option{-gnatf} switch yields 4961 4962@smallexample 4963e.adb:7:07: "V" is undefined 4964e.adb:8:07: "V" is undefined 4965e.adb:8:12: "V" is undefined 4966e.adb:8:16: "V" is undefined 4967e.adb:9:07: "V" is undefined 4968e.adb:9:12: "V" is undefined 4969@end smallexample 4970 4971@noindent 4972The @option{-gnatf} switch also generates additional information for 4973some error messages. Some examples are: 4974 4975@itemize @bullet 4976@item 4977Details on possibly non-portable unchecked conversion 4978@item 4979List possible interpretations for ambiguous calls 4980@item 4981Additional details on incorrect parameters 4982@end itemize 4983 4984@item -gnatjnn 4985@cindex @option{-gnatjnn} (@command{gcc}) 4986In normal operation mode (or if @option{-gnatj0} is used, then error messages 4987with continuation lines are treated as though the continuation lines were 4988separate messages (and so a warning with two continuation lines counts as 4989three warnings, and is listed as three separate messages). 4990 4991If the @option{-gnatjnn} switch is used with a positive value for nn, then 4992messages are output in a different manner. A message and all its continuation 4993lines are treated as a unit, and count as only one warning or message in the 4994statistics totals. Furthermore, the message is reformatted so that no line 4995is longer than nn characters. 4996 4997@item -gnatq 4998@cindex @option{-gnatq} (@command{gcc}) 4999@ifclear vms 5000The @code{q} stands for quit (really ``don't quit''). 5001@end ifclear 5002In normal operation mode, the compiler first parses the program and 5003determines if there are any syntax errors. If there are, appropriate 5004error messages are generated and compilation is immediately terminated. 5005This switch tells 5006GNAT to continue with semantic analysis even if syntax errors have been 5007found. This may enable the detection of more errors in a single run. On 5008the other hand, the semantic analyzer is more likely to encounter some 5009internal fatal error when given a syntactically invalid tree. 5010 5011@item -gnatQ 5012@cindex @option{-gnatQ} (@command{gcc}) 5013In normal operation mode, the @file{ALI} file is not generated if any 5014illegalities are detected in the program. The use of @option{-gnatQ} forces 5015generation of the @file{ALI} file. This file is marked as being in 5016error, so it cannot be used for binding purposes, but it does contain 5017reasonably complete cross-reference information, and thus may be useful 5018for use by tools (e.g., semantic browsing tools or integrated development 5019environments) that are driven from the @file{ALI} file. This switch 5020implies @option{-gnatq}, since the semantic phase must be run to get a 5021meaningful ALI file. 5022 5023In addition, if @option{-gnatt} is also specified, then the tree file is 5024generated even if there are illegalities. It may be useful in this case 5025to also specify @option{-gnatq} to ensure that full semantic processing 5026occurs. The resulting tree file can be processed by ASIS, for the purpose 5027of providing partial information about illegal units, but if the error 5028causes the tree to be badly malformed, then ASIS may crash during the 5029analysis. 5030 5031When @option{-gnatQ} is used and the generated @file{ALI} file is marked as 5032being in error, @command{gnatmake} will attempt to recompile the source when it 5033finds such an @file{ALI} file, including with switch @option{-gnatc}. 5034 5035Note that @option{-gnatQ} has no effect if @option{-gnats} is specified, 5036since ALI files are never generated if @option{-gnats} is set. 5037 5038@end table 5039 5040@node Warning Message Control 5041@subsection Warning Message Control 5042@cindex Warning messages 5043@noindent 5044In addition to error messages, which correspond to illegalities as defined 5045in the Ada Reference Manual, the compiler detects two kinds of warning 5046situations. 5047 5048First, the compiler considers some constructs suspicious and generates a 5049warning message to alert you to a possible error. Second, if the 5050compiler detects a situation that is sure to raise an exception at 5051run time, it generates a warning message. The following shows an example 5052of warning messages: 5053@smallexample 5054e.adb:4:24: warning: creation of object may raise Storage_Error 5055e.adb:10:17: warning: static value out of range 5056e.adb:10:17: warning: "Constraint_Error" will be raised at run time 5057@end smallexample 5058 5059@noindent 5060GNAT considers a large number of situations as appropriate 5061for the generation of warning messages. As always, warnings are not 5062definite indications of errors. For example, if you do an out-of-range 5063assignment with the deliberate intention of raising a 5064@code{Constraint_Error} exception, then the warning that may be 5065issued does not indicate an error. Some of the situations for which GNAT 5066issues warnings (at least some of the time) are given in the following 5067list. This list is not complete, and new warnings are often added to 5068subsequent versions of GNAT. The list is intended to give a general idea 5069of the kinds of warnings that are generated. 5070 5071@itemize @bullet 5072@item 5073Possible infinitely recursive calls 5074 5075@item 5076Out-of-range values being assigned 5077 5078@item 5079Possible order of elaboration problems 5080 5081@item 5082Assertions (pragma Assert) that are sure to fail 5083 5084@item 5085Unreachable code 5086 5087@item 5088Address clauses with possibly unaligned values, or where an attempt is 5089made to overlay a smaller variable with a larger one. 5090 5091@item 5092Fixed-point type declarations with a null range 5093 5094@item 5095Direct_IO or Sequential_IO instantiated with a type that has access values 5096 5097@item 5098Variables that are never assigned a value 5099 5100@item 5101Variables that are referenced before being initialized 5102 5103@item 5104Task entries with no corresponding @code{accept} statement 5105 5106@item 5107Duplicate accepts for the same task entry in a @code{select} 5108 5109@item 5110Objects that take too much storage 5111 5112@item 5113Unchecked conversion between types of differing sizes 5114 5115@item 5116Missing @code{return} statement along some execution path in a function 5117 5118@item 5119Incorrect (unrecognized) pragmas 5120 5121@item 5122Incorrect external names 5123 5124@item 5125Allocation from empty storage pool 5126 5127@item 5128Potentially blocking operation in protected type 5129 5130@item 5131Suspicious parenthesization of expressions 5132 5133@item 5134Mismatching bounds in an aggregate 5135 5136@item 5137Attempt to return local value by reference 5138 5139@item 5140Premature instantiation of a generic body 5141 5142@item 5143Attempt to pack aliased components 5144 5145@item 5146Out of bounds array subscripts 5147 5148@item 5149Wrong length on string assignment 5150 5151@item 5152Violations of style rules if style checking is enabled 5153 5154@item 5155Unused @code{with} clauses 5156 5157@item 5158@code{Bit_Order} usage that does not have any effect 5159 5160@item 5161@code{Standard.Duration} used to resolve universal fixed expression 5162 5163@item 5164Dereference of possibly null value 5165 5166@item 5167Declaration that is likely to cause storage error 5168 5169@item 5170Internal GNAT unit @code{with}'ed by application unit 5171 5172@item 5173Values known to be out of range at compile time 5174 5175@item 5176Unreferenced labels and variables 5177 5178@item 5179Address overlays that could clobber memory 5180 5181@item 5182Unexpected initialization when address clause present 5183 5184@item 5185Bad alignment for address clause 5186 5187@item 5188Useless type conversions 5189 5190@item 5191Redundant assignment statements and other redundant constructs 5192 5193@item 5194Useless exception handlers 5195 5196@item 5197Accidental hiding of name by child unit 5198 5199@item 5200Access before elaboration detected at compile time 5201 5202@item 5203A range in a @code{for} loop that is known to be null or might be null 5204 5205@end itemize 5206 5207@noindent 5208The following section lists compiler switches that are available 5209to control the handling of warning messages. It is also possible 5210to exercise much finer control over what warnings are issued and 5211suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,, 5212gnat_rm, GNAT Reference manual}. 5213 5214@table @option 5215@c !sort! 5216@item -gnatwa 5217@emph{Activate most optional warnings.} 5218@cindex @option{-gnatwa} (@command{gcc}) 5219This switch activates most optional warning messages. See the remaining list 5220in this section for details on optional warning messages that can be 5221individually controlled. The warnings that are not turned on by this 5222switch are 5223@option{-gnatwd} (implicit dereferencing), 5224@option{-gnatwh} (hiding), 5225@ifclear vms 5226@option{-gnatw.d} (tag warnings with -gnatw switch) 5227@end ifclear 5228@option{-gnatw.h} (holes (gaps) in record layouts) 5229@option{-gnatw.i} (overlapping actuals), 5230@option{-gnatw.k} (redefinition of names in standard), 5231@option{-gnatwl} (elaboration warnings), 5232@option{-gnatw.l} (inherited aspects), 5233@option{-gnatw.o} (warn on values set by out parameters ignored), 5234@option{-gnatwt} (tracking of deleted conditional code) 5235and @option{-gnatw.u} (unordered enumeration), 5236All other optional warnings are turned on. 5237 5238@item -gnatwA 5239@emph{Suppress all optional errors.} 5240@cindex @option{-gnatwA} (@command{gcc}) 5241This switch suppresses all optional warning messages, see remaining list 5242in this section for details on optional warning messages that can be 5243individually controlled. Note that unlike switch @option{-gnatws}, the 5244use of switch @option{-gnatwA} does not suppress warnings that are 5245normally given unconditionally and cannot be individually controlled 5246(for example, the warning about a missing exit path in a function). 5247Also, again unlike switch @option{-gnatws}, warnings suppressed by 5248the use of switch @option{-gnatwA} can be individually turned back 5249on. For example the use of switch @option{-gnatwA} followed by 5250switch @option{-gnatwd} will suppress all optional warnings except 5251the warnings for implicit dereferencing. 5252 5253@item -gnatw.a 5254@emph{Activate warnings on failing assertions.} 5255@cindex @option{-gnatw.a} (@command{gcc}) 5256@cindex Assert failures 5257This switch activates warnings for assertions where the compiler can tell at 5258compile time that the assertion will fail. Note that this warning is given 5259even if assertions are disabled. The default is that such warnings are 5260generated. 5261 5262@item -gnatw.A 5263@emph{Suppress warnings on failing assertions.} 5264@cindex @option{-gnatw.A} (@command{gcc}) 5265@cindex Assert failures 5266This switch suppresses warnings for assertions where the compiler can tell at 5267compile time that the assertion will fail. 5268 5269@item -gnatwb 5270@emph{Activate warnings on bad fixed values.} 5271@cindex @option{-gnatwb} (@command{gcc}) 5272@cindex Bad fixed values 5273@cindex Fixed-point Small value 5274@cindex Small value 5275This switch activates warnings for static fixed-point expressions whose 5276value is not an exact multiple of Small. Such values are implementation 5277dependent, since an implementation is free to choose either of the multiples 5278that surround the value. GNAT always chooses the closer one, but this is not 5279required behavior, and it is better to specify a value that is an exact 5280multiple, ensuring predictable execution. The default is that such warnings 5281are not generated. 5282 5283@item -gnatwB 5284@emph{Suppress warnings on bad fixed values.} 5285@cindex @option{-gnatwB} (@command{gcc}) 5286This switch suppresses warnings for static fixed-point expressions whose 5287value is not an exact multiple of Small. 5288 5289@item -gnatw.b 5290@emph{Activate warnings on biased representation.} 5291@cindex @option{-gnatw.b} (@command{gcc}) 5292@cindex Biased representation 5293This switch activates warnings when a size clause, value size clause, component 5294clause, or component size clause forces the use of biased representation for an 5295integer type (e.g. representing a range of 10..11 in a single bit by using 0/1 5296to represent 10/11). The default is that such warnings are generated. 5297 5298@item -gnatw.B 5299@emph{Suppress warnings on biased representation.} 5300@cindex @option{-gnatwB} (@command{gcc}) 5301This switch suppresses warnings for representation clauses that force the use 5302of biased representation. 5303 5304@item -gnatwc 5305@emph{Activate warnings on conditionals.} 5306@cindex @option{-gnatwc} (@command{gcc}) 5307@cindex Conditionals, constant 5308This switch activates warnings for conditional expressions used in 5309tests that are known to be True or False at compile time. The default 5310is that such warnings are not generated. 5311Note that this warning does 5312not get issued for the use of boolean variables or constants whose 5313values are known at compile time, since this is a standard technique 5314for conditional compilation in Ada, and this would generate too many 5315false positive warnings. 5316 5317This warning option also activates a special test for comparisons using 5318the operators ``>='' and`` <=''. 5319If the compiler can tell that only the equality condition is possible, 5320then it will warn that the ``>'' or ``<'' part of the test 5321is useless and that the operator could be replaced by ``=''. 5322An example would be comparing a @code{Natural} variable <= 0. 5323 5324This warning option also generates warnings if 5325one or both tests is optimized away in a membership test for integer 5326values if the result can be determined at compile time. Range tests on 5327enumeration types are not included, since it is common for such tests 5328to include an end point. 5329 5330This warning can also be turned on using @option{-gnatwa}. 5331 5332@item -gnatwC 5333@emph{Suppress warnings on conditionals.} 5334@cindex @option{-gnatwC} (@command{gcc}) 5335This switch suppresses warnings for conditional expressions used in 5336tests that are known to be True or False at compile time. 5337 5338@item -gnatw.c 5339@emph{Activate warnings on missing component clauses.} 5340@cindex @option{-gnatw.c} (@command{gcc}) 5341@cindex Component clause, missing 5342This switch activates warnings for record components where a record 5343representation clause is present and has component clauses for the 5344majority, but not all, of the components. A warning is given for each 5345component for which no component clause is present. 5346 5347This warning can also be turned on using @option{-gnatwa}. 5348 5349@item -gnatw.C 5350@emph{Suppress warnings on missing component clauses.} 5351@cindex @option{-gnatwC} (@command{gcc}) 5352This switch suppresses warnings for record components that are 5353missing a component clause in the situation described above. 5354 5355@item -gnatwd 5356@emph{Activate warnings on implicit dereferencing.} 5357@cindex @option{-gnatwd} (@command{gcc}) 5358If this switch is set, then the use of a prefix of an access type 5359in an indexed component, slice, or selected component without an 5360explicit @code{.all} will generate a warning. With this warning 5361enabled, access checks occur only at points where an explicit 5362@code{.all} appears in the source code (assuming no warnings are 5363generated as a result of this switch). The default is that such 5364warnings are not generated. 5365Note that @option{-gnatwa} does not affect the setting of 5366this warning option. 5367 5368@item -gnatwD 5369@emph{Suppress warnings on implicit dereferencing.} 5370@cindex @option{-gnatwD} (@command{gcc}) 5371@cindex Implicit dereferencing 5372@cindex Dereferencing, implicit 5373This switch suppresses warnings for implicit dereferences in 5374indexed components, slices, and selected components. 5375 5376@ifclear vms 5377@item -gnatw.d 5378@emph{Activate tagging of warning messages.} 5379@cindex @option{-gnatw.d} (@command{gcc}) 5380If this switch is set, then warning messages are tagged, either with 5381the string ``@option{-gnatw?}'' showing which switch controls the warning, 5382or with ``[enabled by default]'' if the warning is not under control of a 5383specific @option{-gnatw?} switch. This mode is off by default, and is not 5384affected by the use of @code{-gnatwa}. 5385 5386@item -gnatw.D 5387@emph{Deactivate tagging of warning messages.} 5388@cindex @option{-gnatw.d} (@command{gcc}) 5389If this switch is set, then warning messages return to the default 5390mode in which warnings are not tagged as described above for 5391@code{-gnatw.d}. 5392@end ifclear 5393 5394@item -gnatwe 5395@emph{Treat warnings and style checks as errors.} 5396@cindex @option{-gnatwe} (@command{gcc}) 5397@cindex Warnings, treat as error 5398This switch causes warning messages and style check messages to be 5399treated as errors. 5400The warning string still appears, but the warning messages are counted 5401as errors, and prevent the generation of an object file. Note that this 5402is the only -gnatw switch that affects the handling of style check messages. 5403 5404@item -gnatw.e 5405@emph{Activate every optional warning} 5406@cindex @option{-gnatw.e} (@command{gcc}) 5407@cindex Warnings, activate every optional warning 5408This switch activates all optional warnings, including those which 5409are not activated by @code{-gnatwa}. The use of this switch is not 5410recommended for normal use. If you turn this switch on, it is almost 5411certain that you will get large numbers of useless warnings. The 5412warnings that are excluded from @code{-gnatwa} are typically highly 5413specialized warnings that are suitable for use only in code that has 5414been specifically designed according to specialized coding rules. 5415 5416@item -gnatwf 5417@emph{Activate warnings on unreferenced formals.} 5418@cindex @option{-gnatwf} (@command{gcc}) 5419@cindex Formals, unreferenced 5420This switch causes a warning to be generated if a formal parameter 5421is not referenced in the body of the subprogram. This warning can 5422also be turned on using @option{-gnatwa} or @option{-gnatwu}. The 5423default is that these warnings are not generated. 5424 5425@item -gnatwF 5426@emph{Suppress warnings on unreferenced formals.} 5427@cindex @option{-gnatwF} (@command{gcc}) 5428This switch suppresses warnings for unreferenced formal 5429parameters. Note that the 5430combination @option{-gnatwu} followed by @option{-gnatwF} has the 5431effect of warning on unreferenced entities other than subprogram 5432formals. 5433 5434@item -gnatwg 5435@emph{Activate warnings on unrecognized pragmas.} 5436@cindex @option{-gnatwg} (@command{gcc}) 5437@cindex Pragmas, unrecognized 5438This switch causes a warning to be generated if an unrecognized 5439pragma is encountered. Apart from issuing this warning, the 5440pragma is ignored and has no effect. This warning can 5441also be turned on using @option{-gnatwa}. The default 5442is that such warnings are issued (satisfying the Ada Reference 5443Manual requirement that such warnings appear). 5444 5445@item -gnatwG 5446@emph{Suppress warnings on unrecognized pragmas.} 5447@cindex @option{-gnatwG} (@command{gcc}) 5448This switch suppresses warnings for unrecognized pragmas. 5449 5450@item -gnatwh 5451@emph{Activate warnings on hiding.} 5452@cindex @option{-gnatwh} (@command{gcc}) 5453@cindex Hiding of Declarations 5454This switch activates warnings on hiding declarations. 5455A declaration is considered hiding 5456if it is for a non-overloadable entity, and it declares an entity with the 5457same name as some other entity that is directly or use-visible. The default 5458is that such warnings are not generated. 5459Note that @option{-gnatwa} does not affect the setting of this warning option. 5460 5461@item -gnatwH 5462@emph{Suppress warnings on hiding.} 5463@cindex @option{-gnatwH} (@command{gcc}) 5464This switch suppresses warnings on hiding declarations. 5465 5466@item -gnatw.h 5467@emph{Activate warnings on holes/gaps in records.} 5468@cindex @option{-gnatw.h} (@command{gcc}) 5469@cindex Record Representation (gaps) 5470This switch activates warnings on component clauses in record 5471representation clauses that leave holes (gaps) in the record layout. 5472If this warning option is active, then record representation clauses 5473should specify a contiguous layout, adding unused fill fields if needed. 5474Note that @option{-gnatwa} does not affect the setting of this warning option. 5475 5476@item -gnatw.H 5477@emph{Suppress warnings on holes/gaps in records.} 5478@cindex @option{-gnatw.H} (@command{gcc}) 5479This switch suppresses warnings on component clauses in record 5480representation clauses that leave holes (haps) in the record layout. 5481 5482@item -gnatwi 5483@emph{Activate warnings on implementation units.} 5484@cindex @option{-gnatwi} (@command{gcc}) 5485This switch activates warnings for a @code{with} of an internal GNAT 5486implementation unit, defined as any unit from the @code{Ada}, 5487@code{Interfaces}, @code{GNAT}, 5488^^@code{DEC},^ or @code{System} 5489hierarchies that is not 5490documented in either the Ada Reference Manual or the GNAT 5491Programmer's Reference Manual. Such units are intended only 5492for internal implementation purposes and should not be @code{with}'ed 5493by user programs. The default is that such warnings are generated 5494This warning can also be turned on using @option{-gnatwa}. 5495 5496@item -gnatwI 5497@emph{Disable warnings on implementation units.} 5498@cindex @option{-gnatwI} (@command{gcc}) 5499This switch disables warnings for a @code{with} of an internal GNAT 5500implementation unit. 5501 5502@item -gnatw.i 5503@emph{Activate warnings on overlapping actuals.} 5504@cindex @option{-gnatw.i} (@command{gcc}) 5505This switch enables a warning on statically detectable overlapping actuals in 5506a subprogram call, when one of the actuals is an in-out parameter, and the 5507types of the actuals are not by-copy types. The warning is off by default, 5508and is not included under -gnatwa. 5509 5510@item -gnatw.I 5511@emph{Disable warnings on overlapping actuals.} 5512@cindex @option{-gnatw.I} (@command{gcc}) 5513This switch disables warnings on overlapping actuals in a call.. 5514 5515@item -gnatwj 5516@emph{Activate warnings on obsolescent features (Annex J).} 5517@cindex @option{-gnatwj} (@command{gcc}) 5518@cindex Features, obsolescent 5519@cindex Obsolescent features 5520If this warning option is activated, then warnings are generated for 5521calls to subprograms marked with @code{pragma Obsolescent} and 5522for use of features in Annex J of the Ada Reference Manual. In the 5523case of Annex J, not all features are flagged. In particular use 5524of the renamed packages (like @code{Text_IO}) and use of package 5525@code{ASCII} are not flagged, since these are very common and 5526would generate many annoying positive warnings. The default is that 5527such warnings are not generated. This warning is also turned on by 5528the use of @option{-gnatwa}. 5529 5530In addition to the above cases, warnings are also generated for 5531GNAT features that have been provided in past versions but which 5532have been superseded (typically by features in the new Ada standard). 5533For example, @code{pragma Ravenscar} will be flagged since its 5534function is replaced by @code{pragma Profile(Ravenscar)}, and 5535@code{pragma Interface_Name} will be flagged since its function 5536is replaced by @code{pragma Import}. 5537 5538Note that this warning option functions differently from the 5539restriction @code{No_Obsolescent_Features} in two respects. 5540First, the restriction applies only to annex J features. 5541Second, the restriction does flag uses of package @code{ASCII}. 5542 5543@item -gnatwJ 5544@emph{Suppress warnings on obsolescent features (Annex J).} 5545@cindex @option{-gnatwJ} (@command{gcc}) 5546This switch disables warnings on use of obsolescent features. 5547 5548@item -gnatwk 5549@emph{Activate warnings on variables that could be constants.} 5550@cindex @option{-gnatwk} (@command{gcc}) 5551This switch activates warnings for variables that are initialized but 5552never modified, and then could be declared constants. The default is that 5553such warnings are not given. 5554This warning can also be turned on using @option{-gnatwa}. 5555 5556@item -gnatwK 5557@emph{Suppress warnings on variables that could be constants.} 5558@cindex @option{-gnatwK} (@command{gcc}) 5559This switch disables warnings on variables that could be declared constants. 5560 5561@item -gnatw.k 5562@emph{Activate warnings on redefinition of names in standard.} 5563@cindex @option{-gnatw.k} (@command{gcc}) 5564This switch activates warnings for declarations that declare a name that 5565is defined in package Standard. Such declarations can be confusing, 5566especially since the names in package Standard continue to be directly 5567visible, meaning that use visibiliy on such redeclared names does not 5568work as expected. Names of discriminants and components in records are 5569not included in this check. 5570This warning is not part of the warnings activated by @option{-gnatwa}. 5571It must be explicitly activated. 5572 5573@item -gnatw.K 5574@emph{Suppress warnings on variables that could be constants.} 5575@cindex @option{-gnatwK} (@command{gcc}) 5576This switch activates warnings for declarations that declare a name that 5577is defined in package Standard. 5578 5579@item -gnatwl 5580@emph{Activate warnings for elaboration pragmas.} 5581@cindex @option{-gnatwl} (@command{gcc}) 5582@cindex Elaboration, warnings 5583This switch activates warnings on missing 5584@code{Elaborate_All} and @code{Elaborate} pragmas. 5585See the section in this guide on elaboration checking for details on 5586when such pragmas should be used. In dynamic elaboration mode, this switch 5587generations warnings about the need to add elaboration pragmas. Note however, 5588that if you blindly follow these warnings, and add @code{Elaborate_All} 5589warnings wherever they are recommended, you basically end up with the 5590equivalent of the static elaboration model, which may not be what you want for 5591legacy code for which the static model does not work. 5592 5593For the static model, the messages generated are labeled "info:" (for 5594information messages). They are not warnings to add elaboration pragmas, 5595merely informational messages showing what implicit elaboration pragmas 5596have been added, for use in analyzing elaboration circularity problems. 5597 5598Warnings are also generated if you 5599are using the static mode of elaboration, and a @code{pragma Elaborate} 5600is encountered. The default is that such warnings 5601are not generated. 5602This warning is not automatically turned on by the use of @option{-gnatwa}. 5603 5604@item -gnatwL 5605@emph{Suppress warnings for elaboration pragmas.} 5606@cindex @option{-gnatwL} (@command{gcc}) 5607This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas. 5608See the section in this guide on elaboration checking for details on 5609when such pragmas should be used. 5610 5611@item -gnatw.l 5612@emph{List inherited aspects.} 5613@cindex @option{-gnatw.l} (@command{gcc}) 5614This switch causes the compiler to list inherited invariants, 5615preconditions, and postconditions from Type_Invariant'Class, Invariant'Class, 5616Pre'Class, and Post'Class aspects. Also list inherited subtype predicates. 5617These messages are not automatically turned on by the use of @option{-gnatwa}. 5618 5619@item -gnatw.L 5620@emph{Suppress listing of inherited aspects.} 5621@cindex @option{-gnatw.L} (@command{gcc}) 5622This switch suppresses listing of inherited aspects. 5623 5624@item -gnatwm 5625@emph{Activate warnings on modified but unreferenced variables.} 5626@cindex @option{-gnatwm} (@command{gcc}) 5627This switch activates warnings for variables that are assigned (using 5628an initialization value or with one or more assignment statements) but 5629whose value is never read. The warning is suppressed for volatile 5630variables and also for variables that are renamings of other variables 5631or for which an address clause is given. 5632This warning can also be turned on using @option{-gnatwa}. 5633The default is that these warnings are not given. 5634 5635@item -gnatwM 5636@emph{Disable warnings on modified but unreferenced variables.} 5637@cindex @option{-gnatwM} (@command{gcc}) 5638This switch disables warnings for variables that are assigned or 5639initialized, but never read. 5640 5641@item -gnatw.m 5642@emph{Activate warnings on suspicious modulus values.} 5643@cindex @option{-gnatw.m} (@command{gcc}) 5644This switch activates warnings for modulus values that seem suspicious. 5645The cases caught are where the size is the same as the modulus (e.g. 5646a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64 5647with no size clause. The guess in both cases is that 2**x was intended 5648rather than x. In addition expressions of the form 2*x for small x 5649generate a warning (the almost certainly accurate guess being that 56502**x was intended). The default is that these warnings are given. 5651 5652@item -gnatw.M 5653@emph{Disable warnings on suspicious modulus values.} 5654@cindex @option{-gnatw.M} (@command{gcc}) 5655This switch disables warnings for suspicious modulus values. 5656 5657@item -gnatwn 5658@emph{Set normal warnings mode.} 5659@cindex @option{-gnatwn} (@command{gcc}) 5660This switch sets normal warning mode, in which enabled warnings are 5661issued and treated as warnings rather than errors. This is the default 5662mode. the switch @option{-gnatwn} can be used to cancel the effect of 5663an explicit @option{-gnatws} or 5664@option{-gnatwe}. It also cancels the effect of the 5665implicit @option{-gnatwe} that is activated by the 5666use of @option{-gnatg}. 5667 5668@item -gnatwo 5669@emph{Activate warnings on address clause overlays.} 5670@cindex @option{-gnatwo} (@command{gcc}) 5671@cindex Address Clauses, warnings 5672This switch activates warnings for possibly unintended initialization 5673effects of defining address clauses that cause one variable to overlap 5674another. The default is that such warnings are generated. 5675This warning can also be turned on using @option{-gnatwa}. 5676 5677@item -gnatwO 5678@emph{Suppress warnings on address clause overlays.} 5679@cindex @option{-gnatwO} (@command{gcc}) 5680This switch suppresses warnings on possibly unintended initialization 5681effects of defining address clauses that cause one variable to overlap 5682another. 5683 5684@item -gnatw.o 5685@emph{Activate warnings on modified but unreferenced out parameters.} 5686@cindex @option{-gnatw.o} (@command{gcc}) 5687This switch activates warnings for variables that are modified by using 5688them as actuals for a call to a procedure with an out mode formal, where 5689the resulting assigned value is never read. It is applicable in the case 5690where there is more than one out mode formal. If there is only one out 5691mode formal, the warning is issued by default (controlled by -gnatwu). 5692The warning is suppressed for volatile 5693variables and also for variables that are renamings of other variables 5694or for which an address clause is given. 5695The default is that these warnings are not given. Note that this warning 5696is not included in -gnatwa, it must be activated explicitly. 5697 5698@item -gnatw.O 5699@emph{Disable warnings on modified but unreferenced out parameters.} 5700@cindex @option{-gnatw.O} (@command{gcc}) 5701This switch suppresses warnings for variables that are modified by using 5702them as actuals for a call to a procedure with an out mode formal, where 5703the resulting assigned value is never read. 5704 5705@item -gnatwp 5706@emph{Activate warnings on ineffective pragma Inlines.} 5707@cindex @option{-gnatwp} (@command{gcc}) 5708@cindex Inlining, warnings 5709This switch activates warnings for failure of front end inlining 5710(activated by @option{-gnatN}) to inline a particular call. There are 5711many reasons for not being able to inline a call, including most 5712commonly that the call is too complex to inline. The default is 5713that such warnings are not given. 5714This warning can also be turned on using @option{-gnatwa}. 5715Warnings on ineffective inlining by the gcc back-end can be activated 5716separately, using the gcc switch -Winline. 5717 5718@item -gnatwP 5719@emph{Suppress warnings on ineffective pragma Inlines.} 5720@cindex @option{-gnatwP} (@command{gcc}) 5721This switch suppresses warnings on ineffective pragma Inlines. If the 5722inlining mechanism cannot inline a call, it will simply ignore the 5723request silently. 5724 5725@item -gnatw.p 5726@emph{Activate warnings on parameter ordering.} 5727@cindex @option{-gnatw.p} (@command{gcc}) 5728@cindex Parameter order, warnings 5729This switch activates warnings for cases of suspicious parameter 5730ordering when the list of arguments are all simple identifiers that 5731match the names of the formals, but are in a different order. The 5732warning is suppressed if any use of named parameter notation is used, 5733so this is the appropriate way to suppress a false positive (and 5734serves to emphasize that the "misordering" is deliberate). The 5735default is 5736that such warnings are not given. 5737This warning can also be turned on using @option{-gnatwa}. 5738 5739@item -gnatw.P 5740@emph{Suppress warnings on parameter ordering.} 5741@cindex @option{-gnatw.P} (@command{gcc}) 5742This switch suppresses warnings on cases of suspicious parameter 5743ordering. 5744 5745@item -gnatwq 5746@emph{Activate warnings on questionable missing parentheses.} 5747@cindex @option{-gnatwq} (@command{gcc}) 5748@cindex Parentheses, warnings 5749This switch activates warnings for cases where parentheses are not used and 5750the result is potential ambiguity from a readers point of view. For example 5751(not a > b) when a and b are modular means ((not a) > b) and very likely the 5752programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and 5753quite likely ((-x) mod 5) was intended. In such situations it seems best to 5754follow the rule of always parenthesizing to make the association clear, and 5755this warning switch warns if such parentheses are not present. The default 5756is that these warnings are given. 5757This warning can also be turned on using @option{-gnatwa}. 5758 5759@item -gnatwQ 5760@emph{Suppress warnings on questionable missing parentheses.} 5761@cindex @option{-gnatwQ} (@command{gcc}) 5762This switch suppresses warnings for cases where the association is not 5763clear and the use of parentheses is preferred. 5764 5765@item -gnatwr 5766@emph{Activate warnings on redundant constructs.} 5767@cindex @option{-gnatwr} (@command{gcc}) 5768This switch activates warnings for redundant constructs. The following 5769is the current list of constructs regarded as redundant: 5770 5771@itemize @bullet 5772@item 5773Assignment of an item to itself. 5774@item 5775Type conversion that converts an expression to its own type. 5776@item 5777Use of the attribute @code{Base} where @code{typ'Base} is the same 5778as @code{typ}. 5779@item 5780Use of pragma @code{Pack} when all components are placed by a record 5781representation clause. 5782@item 5783Exception handler containing only a reraise statement (raise with no 5784operand) which has no effect. 5785@item 5786Use of the operator abs on an operand that is known at compile time 5787to be non-negative 5788@item 5789Comparison of boolean expressions to an explicit True value. 5790@end itemize 5791 5792This warning can also be turned on using @option{-gnatwa}. 5793The default is that warnings for redundant constructs are not given. 5794 5795@item -gnatwR 5796@emph{Suppress warnings on redundant constructs.} 5797@cindex @option{-gnatwR} (@command{gcc}) 5798This switch suppresses warnings for redundant constructs. 5799 5800@item -gnatw.r 5801@emph{Activate warnings for object renaming function.} 5802@cindex @option{-gnatw.r} (@command{gcc}) 5803This switch activates warnings for an object renaming that renames a 5804function call, which is equivalent to a constant declaration (as 5805opposed to renaming the function itself). The default is that these 5806warnings are given. This warning can also be turned on using 5807@option{-gnatwa}. 5808 5809@item -gnatw.R 5810@emph{Suppress warnings for object renaming function.} 5811@cindex @option{-gnatwT} (@command{gcc}) 5812This switch suppresses warnings for object renaming function. 5813 5814@item -gnatws 5815@emph{Suppress all warnings.} 5816@cindex @option{-gnatws} (@command{gcc}) 5817This switch completely suppresses the 5818output of all warning messages from the GNAT front end, including 5819both warnings that can be controlled by switches described in this 5820section, and those that are normally given unconditionally. The 5821effect of this suppress action can only be cancelled by a subsequent 5822use of the switch @option{-gnatwn}. 5823 5824Note that switch @option{-gnatws} does not suppress 5825warnings from the @command{gcc} back end. 5826To suppress these back end warnings as well, use the switch @option{-w} 5827in addition to @option{-gnatws}. Also this switch has no effect on the 5828handling of style check messages. 5829 5830@item -gnatw.s 5831@emph{Activate warnings on overridden size clauses.} 5832@cindex @option{-gnatw.s} (@command{gcc}) 5833@cindex Record Representation (component sizes) 5834This switch activates warnings on component clauses in record 5835representation clauses where the length given overrides that 5836specified by an explicit size clause for the component type. A 5837warning is similarly given in the array case if a specified 5838component size overrides an explicit size clause for the array 5839component type. 5840Note that @option{-gnatwa} does not affect the setting of this warning option. 5841 5842@item -gnatw.S 5843@emph{Suppress warnings on overridden size clauses.} 5844@cindex @option{-gnatw.S} (@command{gcc}) 5845This switch suppresses warnings on component clauses in record 5846representation clauses that override size clauses, and similar 5847warnings when an array component size overrides a size clause. 5848 5849@item -gnatwt 5850@emph{Activate warnings for tracking of deleted conditional code.} 5851@cindex @option{-gnatwt} (@command{gcc}) 5852@cindex Deactivated code, warnings 5853@cindex Deleted code, warnings 5854This switch activates warnings for tracking of code in conditionals (IF and 5855CASE statements) that is detected to be dead code which cannot be executed, and 5856which is removed by the front end. This warning is off by default, and is not 5857turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be 5858useful for detecting deactivated code in certified applications. 5859 5860@item -gnatwT 5861@emph{Suppress warnings for tracking of deleted conditional code.} 5862@cindex @option{-gnatwT} (@command{gcc}) 5863This switch suppresses warnings for tracking of deleted conditional code. 5864 5865@item -gnatw.t 5866@emph{Activate warnings on suspicious contracts.} 5867@cindex @option{-gnatw.t} (@command{gcc}) 5868This switch activates warnings on suspicious postconditions (whether a 5869pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012) 5870and suspicious contract cases (pragma @code{Contract_Case}). A 5871function postcondition or contract case is suspicious when no postcondition 5872or contract case for this function mentions the result of the function. 5873A procedure postcondition or contract case is suspicious when it only 5874refers to the pre-state of the procedure, because in that case it should 5875rather be expressed as a precondition. The default is that such warnings 5876are not generated. This warning can also be turned on using @option{-gnatwa}. 5877 5878@item -gnatw.T 5879@emph{Suppress warnings on suspicious contracts.} 5880@cindex @option{-gnatw.T} (@command{gcc}) 5881This switch suppresses warnings on suspicious postconditions. 5882 5883@item -gnatwu 5884@emph{Activate warnings on unused entities.} 5885@cindex @option{-gnatwu} (@command{gcc}) 5886This switch activates warnings to be generated for entities that 5887are declared but not referenced, and for units that are @code{with}'ed 5888and not 5889referenced. In the case of packages, a warning is also generated if 5890no entities in the package are referenced. This means that if a with'ed 5891package is referenced but the only references are in @code{use} 5892clauses or @code{renames} 5893declarations, a warning is still generated. A warning is also generated 5894for a generic package that is @code{with}'ed but never instantiated. 5895In the case where a package or subprogram body is compiled, and there 5896is a @code{with} on the corresponding spec 5897that is only referenced in the body, 5898a warning is also generated, noting that the 5899@code{with} can be moved to the body. The default is that 5900such warnings are not generated. 5901This switch also activates warnings on unreferenced formals 5902(it includes the effect of @option{-gnatwf}). 5903This warning can also be turned on using @option{-gnatwa}. 5904 5905@item -gnatwU 5906@emph{Suppress warnings on unused entities.} 5907@cindex @option{-gnatwU} (@command{gcc}) 5908This switch suppresses warnings for unused entities and packages. 5909It also turns off warnings on unreferenced formals (and thus includes 5910the effect of @option{-gnatwF}). 5911 5912@item -gnatw.u 5913@emph{Activate warnings on unordered enumeration types.} 5914@cindex @option{-gnatw.u} (@command{gcc}) 5915This switch causes enumeration types to be considered as conceptually 5916unordered, unless an explicit pragma @code{Ordered} is given for the type. 5917The effect is to generate warnings in clients that use explicit comparisons 5918or subranges, since these constructs both treat objects of the type as 5919ordered. (A @emph{client} is defined as a unit that is other than the unit in 5920which the type is declared, or its body or subunits.) Please refer to 5921the description of pragma @code{Ordered} in the 5922@cite{@value{EDITION} Reference Manual} for further details. 5923The default is that such warnings are not generated. 5924This warning is not automatically turned on by the use of @option{-gnatwa}. 5925 5926@item -gnatw.U 5927@emph{Deactivate warnings on unordered enumeration types.} 5928@cindex @option{-gnatw.U} (@command{gcc}) 5929This switch causes all enumeration types to be considered as ordered, so 5930that no warnings are given for comparisons or subranges for any type. 5931 5932@item -gnatwv 5933@emph{Activate warnings on unassigned variables.} 5934@cindex @option{-gnatwv} (@command{gcc}) 5935@cindex Unassigned variable warnings 5936This switch activates warnings for access to variables which 5937may not be properly initialized. The default is that 5938such warnings are generated. 5939This warning can also be turned on using @option{-gnatwa}. 5940 5941@item -gnatwV 5942@emph{Suppress warnings on unassigned variables.} 5943@cindex @option{-gnatwV} (@command{gcc}) 5944This switch suppresses warnings for access to variables which 5945may not be properly initialized. 5946For variables of a composite type, the warning can also be suppressed in 5947Ada 2005 by using a default initialization with a box. For example, if 5948Table is an array of records whose components are only partially uninitialized, 5949then the following code: 5950 5951@smallexample @c ada 5952 Tab : Table := (others => <>); 5953@end smallexample 5954 5955will suppress warnings on subsequent statements that access components 5956of variable Tab. 5957 5958@item -gnatw.v 5959@emph{Activate info messages for non-default bit order.} 5960@cindex @option{-gnatw.v} (@command{gcc}) 5961@cindex bit order warnings 5962This switch activates messages (labeled "info", they are not warnings, 5963just informational messages) about the effects of non-default bit-order 5964on records to which a component clause is applied. The effect of specifying 5965non-default bit ordering is a bit subtle (and changed with Ada 2005), so 5966these messages, which are given by default, are useful in understanding the 5967exact consequences of using this feature. These messages 5968can also be turned on using @option{-gnatwa} 5969 5970@item -gnatw.V 5971@emph{Suppress info messages for non-default bit order.} 5972@cindex @option{-gnatw.V} (@command{gcc}) 5973This switch suppresses information messages for the effects of specifying 5974non-default bit order on record components with component clauses. 5975 5976@item -gnatww 5977@emph{Activate warnings on wrong low bound assumption.} 5978@cindex @option{-gnatww} (@command{gcc}) 5979@cindex String indexing warnings 5980This switch activates warnings for indexing an unconstrained string parameter 5981with a literal or S'Length. This is a case where the code is assuming that the 5982low bound is one, which is in general not true (for example when a slice is 5983passed). The default is that such warnings are generated. 5984This warning can also be turned on using @option{-gnatwa}. 5985 5986@item -gnatwW 5987@emph{Suppress warnings on wrong low bound assumption.} 5988@cindex @option{-gnatwW} (@command{gcc}) 5989This switch suppresses warnings for indexing an unconstrained string parameter 5990with a literal or S'Length. Note that this warning can also be suppressed 5991in a particular case by adding an 5992assertion that the lower bound is 1, 5993as shown in the following example. 5994 5995@smallexample @c ada 5996 procedure K (S : String) is 5997 pragma Assert (S'First = 1); 5998 @dots{} 5999@end smallexample 6000 6001@item -gnatw.w 6002@emph{Activate warnings on unnecessary Warnings Off pragmas} 6003@cindex @option{-gnatw.w} (@command{gcc}) 6004@cindex Warnings Off control 6005This switch activates warnings for use of @code{pragma Warnings (Off, entity)} 6006where either the pragma is entirely useless (because it suppresses no 6007warnings), or it could be replaced by @code{pragma Unreferenced} or 6008@code{pragma Unmodified}. The default is that these warnings are not given. 6009Note that this warning is not included in -gnatwa, it must be 6010activated explicitly. 6011 6012@item -gnatw.W 6013@emph{Suppress warnings on unnecessary Warnings Off pragmas} 6014@cindex @option{-gnatw.W} (@command{gcc}) 6015This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}. 6016 6017@item -gnatwx 6018@emph{Activate warnings on Export/Import pragmas.} 6019@cindex @option{-gnatwx} (@command{gcc}) 6020@cindex Export/Import pragma warnings 6021This switch activates warnings on Export/Import pragmas when 6022the compiler detects a possible conflict between the Ada and 6023foreign language calling sequences. For example, the use of 6024default parameters in a convention C procedure is dubious 6025because the C compiler cannot supply the proper default, so 6026a warning is issued. The default is that such warnings are 6027generated. 6028This warning can also be turned on using @option{-gnatwa}. 6029 6030@item -gnatwX 6031@emph{Suppress warnings on Export/Import pragmas.} 6032@cindex @option{-gnatwX} (@command{gcc}) 6033This switch suppresses warnings on Export/Import pragmas. 6034The sense of this is that you are telling the compiler that 6035you know what you are doing in writing the pragma, and it 6036should not complain at you. 6037 6038@item -gnatw.x 6039@emph{Activate warnings for No_Exception_Propagation mode.} 6040@cindex @option{-gnatwm} (@command{gcc}) 6041This switch activates warnings for exception usage when pragma Restrictions 6042(No_Exception_Propagation) is in effect. Warnings are given for implicit or 6043explicit exception raises which are not covered by a local handler, and for 6044exception handlers which do not cover a local raise. The default is that these 6045warnings are not given. 6046 6047@item -gnatw.X 6048@emph{Disable warnings for No_Exception_Propagation mode.} 6049This switch disables warnings for exception usage when pragma Restrictions 6050(No_Exception_Propagation) is in effect. 6051 6052@item -gnatwy 6053@emph{Activate warnings for Ada compatibility issues.} 6054@cindex @option{-gnatwy} (@command{gcc}) 6055@cindex Ada compatibility issues warnings 6056For the most part, newer versions of Ada are upwards compatible 6057with older versions. For example, Ada 2005 programs will almost 6058always work when compiled as Ada 2012. 6059However there are some exceptions (for example the fact that 6060@code{some} is now a reserved word in Ada 2012). This 6061switch activates several warnings to help in identifying 6062and correcting such incompatibilities. The default is that 6063these warnings are generated. Note that at one point Ada 2005 6064was called Ada 0Y, hence the choice of character. 6065This warning can also be turned on using @option{-gnatwa}. 6066 6067@item -gnatwY 6068@emph{Disable warnings for Ada compatibility issues.} 6069@cindex @option{-gnatwY} (@command{gcc}) 6070@cindex Ada compatibility issues warnings 6071This switch suppresses the warnings intended to help in identifying 6072incompatibilities between Ada language versions. 6073 6074@item -gnatwz 6075@emph{Activate warnings on unchecked conversions.} 6076@cindex @option{-gnatwz} (@command{gcc}) 6077@cindex Unchecked_Conversion warnings 6078This switch activates warnings for unchecked conversions 6079where the types are known at compile time to have different 6080sizes. The default 6081is that such warnings are generated. Warnings are also 6082generated for subprogram pointers with different conventions, 6083and, on VMS only, for data pointers with different conventions. 6084This warning can also be turned on using @option{-gnatwa}. 6085 6086@item -gnatwZ 6087@emph{Suppress warnings on unchecked conversions.} 6088@cindex @option{-gnatwZ} (@command{gcc}) 6089This switch suppresses warnings for unchecked conversions 6090where the types are known at compile time to have different 6091sizes or conventions. 6092 6093@item ^-Wunused^WARNINGS=UNUSED^ 6094@cindex @option{-Wunused} 6095The warnings controlled by the @option{-gnatw} switch are generated by 6096the front end of the compiler. The @option{GCC} back end can provide 6097additional warnings and they are controlled by the @option{-W} switch. 6098For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end 6099warnings for entities that are declared but not referenced. 6100 6101@item ^-Wuninitialized^WARNINGS=UNINITIALIZED^ 6102@cindex @option{-Wuninitialized} 6103Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates 6104the back end warning for uninitialized variables. This switch must be 6105used in conjunction with an optimization level greater than zero. 6106 6107@item -Wstack-usage=@var{len} 6108@cindex @option{-Wstack-usage} 6109Warn if the stack usage of a subprogram might be larger than @var{len} bytes. 6110See @ref{Static Stack Usage Analysis} for details. 6111 6112@item ^-Wall^/ALL_BACK_END_WARNINGS^ 6113@cindex @option{-Wall} 6114This switch enables most warnings from the @option{GCC} back end. 6115The code generator detects a number of warning situations that are missed 6116by the @option{GNAT} front end, and this switch can be used to activate them. 6117The use of this switch also sets the default front end warning mode to 6118@option{-gnatwa}, that is, most front end warnings activated as well. 6119 6120@item ^-w^/NO_BACK_END_WARNINGS^ 6121@cindex @option{-w} 6122Conversely, this switch suppresses warnings from the @option{GCC} back end. 6123The use of this switch also sets the default front end warning mode to 6124@option{-gnatws}, that is, front end warnings suppressed as well. 6125 6126@end table 6127 6128@noindent 6129@ifclear vms 6130A string of warning parameters can be used in the same parameter. For example: 6131 6132@smallexample 6133-gnatwaGe 6134@end smallexample 6135 6136@noindent 6137will turn on all optional warnings except for unrecognized pragma warnings, 6138and also specify that warnings should be treated as errors. 6139@end ifclear 6140 6141When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to: 6142 6143@table @option 6144@c !sort! 6145@item -gnatw.a 6146@item -gnatwB 6147@item -gnatw.b 6148@item -gnatwC 6149@item -gnatw.C 6150@item -gnatwD 6151@item -gnatwF 6152@item -gnatwg 6153@item -gnatwH 6154@item -gnatwi 6155@item -gnatw.I 6156@item -gnatwJ 6157@item -gnatwK 6158@item -gnatwL 6159@item -gnatw.L 6160@item -gnatwM 6161@item -gnatw.m 6162@item -gnatwn 6163@item -gnatwo 6164@item -gnatw.O 6165@item -gnatwP 6166@item -gnatw.P 6167@item -gnatwq 6168@item -gnatwR 6169@item -gnatw.R 6170@item -gnatw.S 6171@item -gnatwT 6172@item -gnatw.T 6173@item -gnatwU 6174@item -gnatwv 6175@item -gnatww 6176@item -gnatw.W 6177@item -gnatwx 6178@item -gnatw.X 6179@item -gnatwy 6180@item -gnatwz 6181 6182@end table 6183 6184@node Debugging and Assertion Control 6185@subsection Debugging and Assertion Control 6186 6187@table @option 6188@item -gnata 6189@cindex @option{-gnata} (@command{gcc}) 6190@findex Assert 6191@findex Debug 6192@cindex Assertions 6193 6194@noindent 6195The pragmas @code{Assert} and @code{Debug} normally have no effect and 6196are ignored. This switch, where @samp{a} stands for assert, causes 6197@code{Assert} and @code{Debug} pragmas to be activated. 6198 6199The pragmas have the form: 6200 6201@smallexample 6202@cartouche 6203 @b{pragma} Assert (@var{Boolean-expression} @r{[}, 6204 @var{static-string-expression}@r{]}) 6205 @b{pragma} Debug (@var{procedure call}) 6206@end cartouche 6207@end smallexample 6208 6209@noindent 6210The @code{Assert} pragma causes @var{Boolean-expression} to be tested. 6211If the result is @code{True}, the pragma has no effect (other than 6212possible side effects from evaluating the expression). If the result is 6213@code{False}, the exception @code{Assert_Failure} declared in the package 6214@code{System.Assertions} is 6215raised (passing @var{static-string-expression}, if present, as the 6216message associated with the exception). If no string expression is 6217given the default is a string giving the file name and line number 6218of the pragma. 6219 6220The @code{Debug} pragma causes @var{procedure} to be called. Note that 6221@code{pragma Debug} may appear within a declaration sequence, allowing 6222debugging procedures to be called between declarations. 6223 6224@ifset vms 6225@item /DEBUG@r{[}=debug-level@r{]} 6226@itemx /NODEBUG 6227Specifies how much debugging information is to be included in 6228the resulting object file where 'debug-level' is one of the following: 6229@table @code 6230@item TRACEBACK 6231Include both debugger symbol records and traceback 6232the object file. 6233This is the default setting. 6234@item ALL 6235Include both debugger symbol records and traceback in 6236object file. 6237@item NONE 6238Excludes both debugger symbol records and traceback 6239the object file. Same as /NODEBUG. 6240@item SYMBOLS 6241Includes only debugger symbol records in the object 6242file. Note that this doesn't include traceback information. 6243@end table 6244@end ifset 6245@end table 6246 6247@node Validity Checking 6248@subsection Validity Checking 6249@findex Validity Checking 6250 6251@noindent 6252The Ada Reference Manual defines the concept of invalid values (see 6253RM 13.9.1). The primary source of invalid values is uninitialized 6254variables. A scalar variable that is left uninitialized may contain 6255an invalid value; the concept of invalid does not apply to access or 6256composite types. 6257 6258It is an error to read an invalid value, but the RM does not require 6259run-time checks to detect such errors, except for some minimal 6260checking to prevent erroneous execution (i.e. unpredictable 6261behavior). This corresponds to the @option{-gnatVd} switch below, 6262which is the default. For example, by default, if the expression of a 6263case statement is invalid, it will raise Constraint_Error rather than 6264causing a wild jump, and if an array index on the left-hand side of an 6265assignment is invalid, it will raise Constraint_Error rather than 6266overwriting an arbitrary memory location. 6267 6268The @option{-gnatVa} may be used to enable additional validity checks, 6269which are not required by the RM. These checks are often very 6270expensive (which is why the RM does not require them). These checks 6271are useful in tracking down uninitialized variables, but they are 6272not usually recommended for production builds. 6273 6274The other @option{-gnatV^@var{x}^^} switches below allow finer-grained 6275control; you can enable whichever validity checks you desire. However, 6276for most debugging purposes, @option{-gnatVa} is sufficient, and the 6277default @option{-gnatVd} (i.e. standard Ada behavior) is usually 6278sufficient for non-debugging use. 6279 6280The @option{-gnatB} switch tells the compiler to assume that all 6281values are valid (that is, within their declared subtype range) 6282except in the context of a use of the Valid attribute. This means 6283the compiler can generate more efficient code, since the range 6284of values is better known at compile time. However, an uninitialized 6285variable can cause wild jumps and memory corruption in this mode. 6286 6287The @option{-gnatV^@var{x}^^} switch allows control over the validity 6288checking mode as described below. 6289@ifclear vms 6290The @code{x} argument is a string of letters that 6291indicate validity checks that are performed or not performed in addition 6292to the default checks required by Ada as described above. 6293@end ifclear 6294@ifset vms 6295The options allowed for this qualifier 6296indicate validity checks that are performed or not performed in addition 6297to the default checks required by Ada as described above. 6298@end ifset 6299 6300@table @option 6301@c !sort! 6302@item -gnatVa 6303@emph{All validity checks.} 6304@cindex @option{-gnatVa} (@command{gcc}) 6305All validity checks are turned on. 6306@ifclear vms 6307That is, @option{-gnatVa} is 6308equivalent to @option{gnatVcdfimorst}. 6309@end ifclear 6310 6311@item -gnatVc 6312@emph{Validity checks for copies.} 6313@cindex @option{-gnatVc} (@command{gcc}) 6314The right hand side of assignments, and the initializing values of 6315object declarations are validity checked. 6316 6317@item -gnatVd 6318@emph{Default (RM) validity checks.} 6319@cindex @option{-gnatVd} (@command{gcc}) 6320Some validity checks are done by default following normal Ada semantics 6321(RM 13.9.1 (9-11)). 6322A check is done in case statements that the expression is within the range 6323of the subtype. If it is not, Constraint_Error is raised. 6324For assignments to array components, a check is done that the expression used 6325as index is within the range. If it is not, Constraint_Error is raised. 6326Both these validity checks may be turned off using switch @option{-gnatVD}. 6327They are turned on by default. If @option{-gnatVD} is specified, a subsequent 6328switch @option{-gnatVd} will leave the checks turned on. 6329Switch @option{-gnatVD} should be used only if you are sure that all such 6330expressions have valid values. If you use this switch and invalid values 6331are present, then the program is erroneous, and wild jumps or memory 6332overwriting may occur. 6333 6334@item -gnatVe 6335@emph{Validity checks for elementary components.} 6336@cindex @option{-gnatVe} (@command{gcc}) 6337In the absence of this switch, assignments to record or array components are 6338not validity checked, even if validity checks for assignments generally 6339(@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not 6340require valid data, but assignment of individual components does. So for 6341example, there is a difference between copying the elements of an array with a 6342slice assignment, compared to assigning element by element in a loop. This 6343switch allows you to turn off validity checking for components, even when they 6344are assigned component by component. 6345 6346@item -gnatVf 6347@emph{Validity checks for floating-point values.} 6348@cindex @option{-gnatVf} (@command{gcc}) 6349In the absence of this switch, validity checking occurs only for discrete 6350values. If @option{-gnatVf} is specified, then validity checking also applies 6351for floating-point values, and NaNs and infinities are considered invalid, 6352as well as out of range values for constrained types. Note that this means 6353that standard IEEE infinity mode is not allowed. The exact contexts 6354in which floating-point values are checked depends on the setting of other 6355options. For example, 6356@option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or 6357@option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^} 6358(the order does not matter) specifies that floating-point parameters of mode 6359@code{in} should be validity checked. 6360 6361@item -gnatVi 6362@emph{Validity checks for @code{in} mode parameters} 6363@cindex @option{-gnatVi} (@command{gcc}) 6364Arguments for parameters of mode @code{in} are validity checked in function 6365and procedure calls at the point of call. 6366 6367@item -gnatVm 6368@emph{Validity checks for @code{in out} mode parameters.} 6369@cindex @option{-gnatVm} (@command{gcc}) 6370Arguments for parameters of mode @code{in out} are validity checked in 6371procedure calls at the point of call. The @code{'m'} here stands for 6372modify, since this concerns parameters that can be modified by the call. 6373Note that there is no specific option to test @code{out} parameters, 6374but any reference within the subprogram will be tested in the usual 6375manner, and if an invalid value is copied back, any reference to it 6376will be subject to validity checking. 6377 6378@item -gnatVn 6379@emph{No validity checks.} 6380@cindex @option{-gnatVn} (@command{gcc}) 6381This switch turns off all validity checking, including the default checking 6382for case statements and left hand side subscripts. Note that the use of 6383the switch @option{-gnatp} suppresses all run-time checks, including 6384validity checks, and thus implies @option{-gnatVn}. When this switch 6385is used, it cancels any other @option{-gnatV} previously issued. 6386 6387@item -gnatVo 6388@emph{Validity checks for operator and attribute operands.} 6389@cindex @option{-gnatVo} (@command{gcc}) 6390Arguments for predefined operators and attributes are validity checked. 6391This includes all operators in package @code{Standard}, 6392the shift operators defined as intrinsic in package @code{Interfaces} 6393and operands for attributes such as @code{Pos}. Checks are also made 6394on individual component values for composite comparisons, and on the 6395expressions in type conversions and qualified expressions. Checks are 6396also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc). 6397 6398@item -gnatVp 6399@emph{Validity checks for parameters.} 6400@cindex @option{-gnatVp} (@command{gcc}) 6401This controls the treatment of parameters within a subprogram (as opposed 6402to @option{-gnatVi} and @option{-gnatVm} which control validity testing 6403of parameters on a call. If either of these call options is used, then 6404normally an assumption is made within a subprogram that the input arguments 6405have been validity checking at the point of call, and do not need checking 6406again within a subprogram). If @option{-gnatVp} is set, then this assumption 6407is not made, and parameters are not assumed to be valid, so their validity 6408will be checked (or rechecked) within the subprogram. 6409 6410@item -gnatVr 6411@emph{Validity checks for function returns.} 6412@cindex @option{-gnatVr} (@command{gcc}) 6413The expression in @code{return} statements in functions is validity 6414checked. 6415 6416@item -gnatVs 6417@emph{Validity checks for subscripts.} 6418@cindex @option{-gnatVs} (@command{gcc}) 6419All subscripts expressions are checked for validity, whether they appear 6420on the right side or left side (in default mode only left side subscripts 6421are validity checked). 6422 6423@item -gnatVt 6424@emph{Validity checks for tests.} 6425@cindex @option{-gnatVt} (@command{gcc}) 6426Expressions used as conditions in @code{if}, @code{while} or @code{exit} 6427statements are checked, as well as guard expressions in entry calls. 6428 6429@end table 6430 6431@noindent 6432The @option{-gnatV} switch may be followed by 6433^a string of letters^a list of options^ 6434to turn on a series of validity checking options. 6435For example, 6436@option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^} 6437specifies that in addition to the default validity checking, copies and 6438function return expressions are to be validity checked. 6439In order to make it easier 6440to specify the desired combination of effects, 6441@ifclear vms 6442the upper case letters @code{CDFIMORST} may 6443be used to turn off the corresponding lower case option. 6444@end ifclear 6445@ifset vms 6446the prefix @code{NO} on an option turns off the corresponding validity 6447checking: 6448@itemize @bullet 6449@item @code{NOCOPIES} 6450@item @code{NODEFAULT} 6451@item @code{NOFLOATS} 6452@item @code{NOIN_PARAMS} 6453@item @code{NOMOD_PARAMS} 6454@item @code{NOOPERANDS} 6455@item @code{NORETURNS} 6456@item @code{NOSUBSCRIPTS} 6457@item @code{NOTESTS} 6458@end itemize 6459@end ifset 6460Thus 6461@option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^} 6462turns on all validity checking options except for 6463checking of @code{@b{in out}} procedure arguments. 6464 6465The specification of additional validity checking generates extra code (and 6466in the case of @option{-gnatVa} the code expansion can be substantial). 6467However, these additional checks can be very useful in detecting 6468uninitialized variables, incorrect use of unchecked conversion, and other 6469errors leading to invalid values. The use of pragma @code{Initialize_Scalars} 6470is useful in conjunction with the extra validity checking, since this 6471ensures that wherever possible uninitialized variables have invalid values. 6472 6473See also the pragma @code{Validity_Checks} which allows modification of 6474the validity checking mode at the program source level, and also allows for 6475temporary disabling of validity checks. 6476 6477@node Style Checking 6478@subsection Style Checking 6479@findex Style checking 6480 6481@noindent 6482The @option{-gnaty^x^(option,option,@dots{})^} switch 6483@cindex @option{-gnaty} (@command{gcc}) 6484causes the compiler to 6485enforce specified style rules. A limited set of style rules has been used 6486in writing the GNAT sources themselves. This switch allows user programs 6487to activate all or some of these checks. If the source program fails a 6488specified style check, an appropriate message is given, preceded by 6489the character sequence ``(style)''. This message does not prevent 6490successful compilation (unless the @option{-gnatwe} switch is used). 6491 6492Note that this is by no means intended to be a general facility for 6493checking arbitrary coding standards. It is simply an embedding of the 6494style rules we have chosen for the GNAT sources. If you are starting 6495a project which does not have established style standards, you may 6496find it useful to adopt the entire set of GNAT coding standards, or 6497some subset of them. If you already have an established set of coding 6498standards, then it may be that selected style checking options do 6499indeed correspond to choices you have made, but for general checking 6500of an existing set of coding rules, you should look to the gnatcheck 6501tool, which is designed for that purpose. 6502 6503@ifset vms 6504@code{(option,option,@dots{})} is a sequence of keywords 6505@end ifset 6506@ifclear vms 6507The string @var{x} is a sequence of letters or digits 6508@end ifclear 6509indicating the particular style 6510checks to be performed. The following checks are defined: 6511 6512@table @option 6513@c !sort! 6514@item 0-9 6515@emph{Specify indentation level.} 6516If a digit from 1-9 appears 6517^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^ 6518then proper indentation is checked, with the digit indicating the 6519indentation level required. A value of zero turns off this style check. 6520The general style of required indentation is as specified by 6521the examples in the Ada Reference Manual. Full line comments must be 6522aligned with the @code{--} starting on a column that is a multiple of 6523the alignment level, or they may be aligned the same way as the following 6524non-blank line (this is useful when full line comments appear in the middle 6525of a statement. 6526 6527@item ^a^ATTRIBUTE^ 6528@emph{Check attribute casing.} 6529Attribute names, including the case of keywords such as @code{digits} 6530used as attributes names, must be written in mixed case, that is, the 6531initial letter and any letter following an underscore must be uppercase. 6532All other letters must be lowercase. 6533 6534@item ^A^ARRAY_INDEXES^ 6535@emph{Use of array index numbers in array attributes.} 6536When using the array attributes First, Last, Range, 6537or Length, the index number must be omitted for one-dimensional arrays 6538and is required for multi-dimensional arrays. 6539 6540@item ^b^BLANKS^ 6541@emph{Blanks not allowed at statement end.} 6542Trailing blanks are not allowed at the end of statements. The purpose of this 6543rule, together with h (no horizontal tabs), is to enforce a canonical format 6544for the use of blanks to separate source tokens. 6545 6546@item ^B^BOOLEAN_OPERATORS^ 6547@emph{Check Boolean operators.} 6548The use of AND/OR operators is not permitted except in the cases of modular 6549operands, array operands, and simple stand-alone boolean variables or 6550boolean constants. In all other cases @code{and then}/@code{or else} are 6551required. 6552 6553@item ^c^COMMENTS^ 6554@emph{Check comments, double space.} 6555Comments must meet the following set of rules: 6556 6557@itemize @bullet 6558 6559@item 6560The ``@code{--}'' that starts the column must either start in column one, 6561or else at least one blank must precede this sequence. 6562 6563@item 6564Comments that follow other tokens on a line must have at least one blank 6565following the ``@code{--}'' at the start of the comment. 6566 6567@item 6568Full line comments must have at least two blanks following the 6569``@code{--}'' that starts the comment, with the following exceptions. 6570 6571@item 6572A line consisting only of the ``@code{--}'' characters, possibly preceded 6573by blanks is permitted. 6574 6575@item 6576A comment starting with ``@code{--x}'' where @code{x} is a special character 6577is permitted. 6578This allows proper processing of the output generated by specialized tools 6579including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK 6580annotation 6581language (where ``@code{--#}'' is used). For the purposes of this rule, a 6582special character is defined as being in one of the ASCII ranges 6583@code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}. 6584Note that this usage is not permitted 6585in GNAT implementation units (i.e., when @option{-gnatg} is used). 6586 6587@item 6588A line consisting entirely of minus signs, possibly preceded by blanks, is 6589permitted. This allows the construction of box comments where lines of minus 6590signs are used to form the top and bottom of the box. 6591 6592@item 6593A comment that starts and ends with ``@code{--}'' is permitted as long as at 6594least one blank follows the initial ``@code{--}''. Together with the preceding 6595rule, this allows the construction of box comments, as shown in the following 6596example: 6597@smallexample 6598--------------------------- 6599-- This is a box comment -- 6600-- with two text lines. -- 6601--------------------------- 6602@end smallexample 6603@end itemize 6604 6605@item ^C^COMMENTS1^ 6606@emph{Check comments, single space.} 6607This is identical to @code{^c^COMMENTS^} except that only one space 6608is required following the @code{--} of a comment instead of two. 6609 6610@item ^d^DOS_LINE_ENDINGS^ 6611@emph{Check no DOS line terminators present.} 6612All lines must be terminated by a single ASCII.LF 6613character (in particular the DOS line terminator sequence CR/LF is not 6614allowed). 6615 6616@item ^e^END^ 6617@emph{Check end/exit labels.} 6618Optional labels on @code{end} statements ending subprograms and on 6619@code{exit} statements exiting named loops, are required to be present. 6620 6621@item ^f^VTABS^ 6622@emph{No form feeds or vertical tabs.} 6623Neither form feeds nor vertical tab characters are permitted 6624in the source text. 6625 6626@item ^g^GNAT^ 6627@emph{GNAT style mode.} 6628The set of style check switches is set to match that used by the GNAT sources. 6629This may be useful when developing code that is eventually intended to be 6630incorporated into GNAT. For further details, see GNAT sources. 6631 6632@item ^h^HTABS^ 6633@emph{No horizontal tabs.} 6634Horizontal tab characters are not permitted in the source text. 6635Together with the b (no blanks at end of line) check, this 6636enforces a canonical form for the use of blanks to separate 6637source tokens. 6638 6639@item ^i^IF_THEN^ 6640@emph{Check if-then layout.} 6641The keyword @code{then} must appear either on the same 6642line as corresponding @code{if}, or on a line on its own, lined 6643up under the @code{if} with at least one non-blank line in between 6644containing all or part of the condition to be tested. 6645 6646@item ^I^IN_MODE^ 6647@emph{check mode IN keywords.} 6648Mode @code{in} (the default mode) is not 6649allowed to be given explicitly. @code{in out} is fine, 6650but not @code{in} on its own. 6651 6652@item ^k^KEYWORD^ 6653@emph{Check keyword casing.} 6654All keywords must be in lower case (with the exception of keywords 6655such as @code{digits} used as attribute names to which this check 6656does not apply). 6657 6658@item ^l^LAYOUT^ 6659@emph{Check layout.} 6660Layout of statement and declaration constructs must follow the 6661recommendations in the Ada Reference Manual, as indicated by the 6662form of the syntax rules. For example an @code{else} keyword must 6663be lined up with the corresponding @code{if} keyword. 6664 6665There are two respects in which the style rule enforced by this check 6666option are more liberal than those in the Ada Reference Manual. First 6667in the case of record declarations, it is permissible to put the 6668@code{record} keyword on the same line as the @code{type} keyword, and 6669then the @code{end} in @code{end record} must line up under @code{type}. 6670This is also permitted when the type declaration is split on two lines. 6671For example, any of the following three layouts is acceptable: 6672 6673@smallexample @c ada 6674@cartouche 6675type q is record 6676 a : integer; 6677 b : integer; 6678end record; 6679 6680type q is 6681 record 6682 a : integer; 6683 b : integer; 6684 end record; 6685 6686type q is 6687 record 6688 a : integer; 6689 b : integer; 6690end record; 6691 6692@end cartouche 6693@end smallexample 6694 6695@noindent 6696Second, in the case of a block statement, a permitted alternative 6697is to put the block label on the same line as the @code{declare} or 6698@code{begin} keyword, and then line the @code{end} keyword up under 6699the block label. For example both the following are permitted: 6700 6701@smallexample @c ada 6702@cartouche 6703Block : declare 6704 A : Integer := 3; 6705begin 6706 Proc (A, A); 6707end Block; 6708 6709Block : 6710 declare 6711 A : Integer := 3; 6712 begin 6713 Proc (A, A); 6714 end Block; 6715@end cartouche 6716@end smallexample 6717 6718@noindent 6719The same alternative format is allowed for loops. For example, both of 6720the following are permitted: 6721 6722@smallexample @c ada 6723@cartouche 6724Clear : while J < 10 loop 6725 A (J) := 0; 6726end loop Clear; 6727 6728Clear : 6729 while J < 10 loop 6730 A (J) := 0; 6731 end loop Clear; 6732@end cartouche 6733@end smallexample 6734 6735@item ^Lnnn^MAX_NESTING=nnn^ 6736@emph{Set maximum nesting level.} 6737The maximum level of nesting of constructs (including subprograms, loops, 6738blocks, packages, and conditionals) may not exceed the given value 6739@option{nnn}. A value of zero disconnects this style check. 6740 6741@item ^m^LINE_LENGTH^ 6742@emph{Check maximum line length.} 6743The length of source lines must not exceed 79 characters, including 6744any trailing blanks. The value of 79 allows convenient display on an 674580 character wide device or window, allowing for possible special 6746treatment of 80 character lines. Note that this count is of 6747characters in the source text. This means that a tab character counts 6748as one character in this count and a wide character sequence counts as 6749a single character (however many bytes are needed in the encoding). 6750 6751@item ^Mnnn^MAX_LENGTH=nnn^ 6752@emph{Set maximum line length.} 6753The length of lines must not exceed the 6754given value @option{nnn}. The maximum value that can be specified is 32767. 6755If neither style option for setting the line length is used, then the 6756default is 255. This also controls the maximum length of lexical elements, 6757where the only restriction is that they must fit on a single line. 6758 6759@item ^n^STANDARD_CASING^ 6760@emph{Check casing of entities in Standard.} 6761Any identifier from Standard must be cased 6762to match the presentation in the Ada Reference Manual (for example, 6763@code{Integer} and @code{ASCII.NUL}). 6764 6765@item ^N^NONE^ 6766@emph{Turn off all style checks.} 6767All style check options are turned off. 6768 6769@item ^o^ORDERED_SUBPROGRAMS^ 6770@emph{Check order of subprogram bodies.} 6771All subprogram bodies in a given scope 6772(e.g.@: a package body) must be in alphabetical order. The ordering 6773rule uses normal Ada rules for comparing strings, ignoring casing 6774of letters, except that if there is a trailing numeric suffix, then 6775the value of this suffix is used in the ordering (e.g.@: Junk2 comes 6776before Junk10). 6777 6778@item ^O^OVERRIDING_INDICATORS^ 6779@emph{Check that overriding subprograms are explicitly marked as such.} 6780The declaration of a primitive operation of a type extension that overrides 6781an inherited operation must carry an overriding indicator. 6782 6783@item ^p^PRAGMA^ 6784@emph{Check pragma casing.} 6785Pragma names must be written in mixed case, that is, the 6786initial letter and any letter following an underscore must be uppercase. 6787All other letters must be lowercase. 6788 6789@item ^r^REFERENCES^ 6790@emph{Check references.} 6791All identifier references must be cased in the same way as the 6792corresponding declaration. No specific casing style is imposed on 6793identifiers. The only requirement is for consistency of references 6794with declarations. 6795 6796@item ^s^SPECS^ 6797@emph{Check separate specs.} 6798Separate declarations (``specs'') are required for subprograms (a 6799body is not allowed to serve as its own declaration). The only 6800exception is that parameterless library level procedures are 6801not required to have a separate declaration. This exception covers 6802the most frequent form of main program procedures. 6803 6804@item ^S^STATEMENTS_AFTER_THEN_ELSE^ 6805@emph{Check no statements after @code{then}/@code{else}.} 6806No statements are allowed 6807on the same line as a @code{then} or @code{else} keyword following the 6808keyword in an @code{if} statement. @code{or else} and @code{and then} are not 6809affected, and a special exception allows a pragma to appear after @code{else}. 6810 6811@item ^t^TOKEN^ 6812@emph{Check token spacing.} 6813The following token spacing rules are enforced: 6814 6815@itemize @bullet 6816 6817@item 6818The keywords @code{abs} and @code{not} must be followed by a space. 6819 6820@item 6821The token @code{=>} must be surrounded by spaces. 6822 6823@item 6824The token @code{<>} must be preceded by a space or a left parenthesis. 6825 6826@item 6827Binary operators other than @code{**} must be surrounded by spaces. 6828There is no restriction on the layout of the @code{**} binary operator. 6829 6830@item 6831Colon must be surrounded by spaces. 6832 6833@item 6834Colon-equal (assignment, initialization) must be surrounded by spaces. 6835 6836@item 6837Comma must be the first non-blank character on the line, or be 6838immediately preceded by a non-blank character, and must be followed 6839by a space. 6840 6841@item 6842If the token preceding a left parenthesis ends with a letter or digit, then 6843a space must separate the two tokens. 6844 6845@item 6846if the token following a right parenthesis starts with a letter or digit, then 6847a space must separate the two tokens. 6848 6849@item 6850A right parenthesis must either be the first non-blank character on 6851a line, or it must be preceded by a non-blank character. 6852 6853@item 6854A semicolon must not be preceded by a space, and must not be followed by 6855a non-blank character. 6856 6857@item 6858A unary plus or minus may not be followed by a space. 6859 6860@item 6861A vertical bar must be surrounded by spaces. 6862@end itemize 6863 6864@item 6865Exactly one blank (and no other white space) must appear between 6866a @code{not} token and a following @code{in} token. 6867 6868@item ^u^UNNECESSARY_BLANK_LINES^ 6869@emph{Check unnecessary blank lines.} 6870Unnecessary blank lines are not allowed. A blank line is considered 6871unnecessary if it appears at the end of the file, or if more than 6872one blank line occurs in sequence. 6873 6874@item ^x^XTRA_PARENS^ 6875@emph{Check extra parentheses.} 6876Unnecessary extra level of parentheses (C-style) are not allowed 6877around conditions in @code{if} statements, @code{while} statements and 6878@code{exit} statements. 6879 6880@item ^y^ALL_BUILTIN^ 6881@emph{Set all standard style check options} 6882This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking 6883options enabled with the exception of @option{-gnatyB}, @option{-gnatyd}, 6884@option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO}, 6885@option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}. 6886 6887@ifclear vms 6888@item - 6889@emph{Remove style check options} 6890This causes any subsequent options in the string to act as canceling the 6891corresponding style check option. To cancel maximum nesting level control, 6892use @option{L} parameter witout any integer value after that, because any 6893digit following @option{-} in the parameter string of the @option{-gnaty} 6894option will be threated as canceling indentation check. The same is true 6895for @option{M} parameter. @option{y} and @option{N} parameters are not 6896allowed after @option{-}. 6897 6898@item + 6899This causes any subsequent options in the string to enable the corresponding 6900style check option. That is, it cancels the effect of a previous ^-^REMOVE^, 6901if any. 6902@end ifclear 6903 6904@ifset vms 6905@item NOxxx 6906@emph{Removing style check options} 6907If the name of a style check is preceded by @option{NO} then the corresponding 6908style check is turned off. For example @option{NOCOMMENTS} turns off style 6909checking for comments. 6910@end ifset 6911@end table 6912 6913@noindent 6914In the above rules, appearing in column one is always permitted, that is, 6915counts as meeting either a requirement for a required preceding space, 6916or as meeting a requirement for no preceding space. 6917 6918Appearing at the end of a line is also always permitted, that is, counts 6919as meeting either a requirement for a following space, or as meeting 6920a requirement for no following space. 6921 6922@noindent 6923If any of these style rules is violated, a message is generated giving 6924details on the violation. The initial characters of such messages are 6925always ``@code{(style)}''. Note that these messages are treated as warning 6926messages, so they normally do not prevent the generation of an object 6927file. The @option{-gnatwe} switch can be used to treat warning messages, 6928including style messages, as fatal errors. 6929 6930The switch 6931@ifclear vms 6932@option{-gnaty} on its own (that is not 6933followed by any letters or digits) is equivalent 6934to the use of @option{-gnatyy} as described above, that is all 6935built-in standard style check options are enabled. 6936 6937@end ifclear 6938@ifset vms 6939/STYLE_CHECKS=ALL_BUILTIN enables all checking options with 6940the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES, 6941XTRA_PARENS, and DOS_LINE_ENDINGS. In addition 6942@end ifset 6943 6944The switch 6945@ifclear vms 6946@option{-gnatyN} 6947@end ifclear 6948@ifset vms 6949/STYLE_CHECKS=NONE 6950@end ifset 6951clears any previously set style checks. 6952 6953@node Run-Time Checks 6954@subsection Run-Time Checks 6955@cindex Division by zero 6956@cindex Access before elaboration 6957@cindex Checks, division by zero 6958@cindex Checks, access before elaboration 6959@cindex Checks, stack overflow checking 6960 6961@noindent 6962By default, the following checks are suppressed: integer overflow 6963checks, stack overflow checks, and checks for access before 6964elaboration on subprogram calls. All other checks, including range 6965checks and array bounds checks, are turned on by default. The 6966following @command{gcc} switches refine this default behavior. 6967 6968@table @option 6969@c !sort! 6970@item -gnatp 6971@cindex @option{-gnatp} (@command{gcc}) 6972@cindex Suppressing checks 6973@cindex Checks, suppressing 6974@findex Suppress 6975This switch causes the unit to be compiled 6976as though @code{pragma Suppress (All_checks)} 6977had been present in the source. Validity checks are also eliminated (in 6978other words @option{-gnatp} also implies @option{-gnatVn}. 6979Use this switch to improve the performance 6980of the code at the expense of safety in the presence of invalid data or 6981program bugs. 6982 6983Note that when checks are suppressed, the compiler is allowed, but not 6984required, to omit the checking code. If the run-time cost of the 6985checking code is zero or near-zero, the compiler will generate it even 6986if checks are suppressed. In particular, if the compiler can prove 6987that a certain check will necessarily fail, it will generate code to 6988do an unconditional ``raise'', even if checks are suppressed. The 6989compiler warns in this case. Another case in which checks may not be 6990eliminated is when they are embedded in certain run time routines such 6991as math library routines. 6992 6993Of course, run-time checks are omitted whenever the compiler can prove 6994that they will not fail, whether or not checks are suppressed. 6995 6996Note that if you suppress a check that would have failed, program 6997execution is erroneous, which means the behavior is totally 6998unpredictable. The program might crash, or print wrong answers, or 6999do anything else. It might even do exactly what you wanted it to do 7000(and then it might start failing mysteriously next week or next 7001year). The compiler will generate code based on the assumption that 7002the condition being checked is true, which can result in disaster if 7003that assumption is wrong. 7004 7005The @option{-gnatp} switch has no effect if a subsequent 7006@option{-gnat-p} switch appears. 7007 7008@item -gnat-p 7009@cindex @option{-gnat-p} (@command{gcc}) 7010@cindex Suppressing checks 7011@cindex Checks, suppressing 7012@findex Suppress 7013This switch cancels the effect of a previous @option{gnatp} switch. 7014 7015@item -gnato?? 7016@cindex @option{-gnato??} (@command{gcc}) 7017@cindex Overflow checks 7018@cindex Overflow mode 7019@cindex Check, overflow 7020This switch controls the mode used for computing intermediate 7021arithmetic integer operations, and also enables overflow checking. 7022For a full description of overflow mode and checking control, see 7023the ``Overflow Check Handling in GNAT'' appendix in this 7024User's Guide. 7025 7026Overflow checks are always enabled by this switch. The argument 7027controls the mode, using the codes 7028 7029@itemize 7030@item 1 = STRICT 7031In STRICT mode, intermediate operations are always done using the 7032base type, and overflow checking ensures that the result is within 7033the base type range. 7034 7035@item 2 = MINIMIZED 7036In MINIMIZED mode, overflows in intermediate operations are avoided 7037where possible by using a larger integer type for the computation 7038(typically @code{Long_Long_Integer}). Overflow checking ensures that 7039the result fits in this larger integer type. 7040 7041@item 3 = ELIMINATED 7042In ELIMINATED mode, overflows in intermediate operations are avoided 7043by using multi-precision arithmetic. In this case, overflow checking 7044has no effect on intermediate operations (since overflow is impossible). 7045@end itemize 7046 7047If two digits are present after @option{-gnato} then the first digit 7048sets the mode for expressions outside assertions, and the second digit 7049sets the mode for expressions within assertions. Here assertions is used 7050in the technical sense (which includes for example precondition and 7051postcondition expressions). 7052 7053If one digit is present, the corresponding mode is applicable to both 7054expressions within and outside assertion expressions. 7055 7056If no digits are present, the default is to enable overflow checks 7057and set STRICT mode for both kinds of expressions. This is compatible 7058with the use of @option{-gnato} in previous versions of GNAT. 7059 7060@findex Machine_Overflows 7061Note that the @option{-gnato??} switch does not affect the code generated 7062for any floating-point operations; it applies only to integer 7063semantics. 7064For floating-point, @value{EDITION} has the @code{Machine_Overflows} 7065attribute set to @code{False} and the normal mode of operation is to 7066generate IEEE NaN and infinite values on overflow or invalid operations 7067(such as dividing 0.0 by 0.0). 7068 7069The reason that we distinguish overflow checking from other kinds of 7070range constraint checking is that a failure of an overflow check, unlike 7071for example the failure of a range check, can result in an incorrect 7072value, but cannot cause random memory destruction (like an out of range 7073subscript), or a wild jump (from an out of range case value). Overflow 7074checking is also quite expensive in time and space, since in general it 7075requires the use of double length arithmetic. 7076 7077Note again that the default is @option{-gnato00}, so overflow checking is 7078not performed in default mode. This means that out of the box, with the 7079default settings, @value{EDITION} does not do all the checks expected from the 7080language description in the Ada Reference Manual. If you want all constraint 7081checks to be performed, as described in this Manual, then you must 7082explicitly use the @option{-gnato??} switch either on the @command{gnatmake} or 7083@command{gcc} command. 7084 7085@item -gnatE 7086@cindex @option{-gnatE} (@command{gcc}) 7087@cindex Elaboration checks 7088@cindex Check, elaboration 7089Enables dynamic checks for access-before-elaboration 7090on subprogram calls and generic instantiations. 7091Note that @option{-gnatE} is not necessary for safety, because in the 7092default mode, GNAT ensures statically that the checks would not fail. 7093For full details of the effect and use of this switch, 7094@xref{Compiling Using gcc}. 7095 7096@item -fstack-check 7097@cindex @option{-fstack-check} (@command{gcc}) 7098@cindex Stack Overflow Checking 7099@cindex Checks, stack overflow checking 7100Activates stack overflow checking. For full details of the effect and use of 7101this switch see @ref{Stack Overflow Checking}. 7102@end table 7103 7104@findex Unsuppress 7105@noindent 7106The setting of these switches only controls the default setting of the 7107checks. You may modify them using either @code{Suppress} (to remove 7108checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in 7109the program source. 7110 7111@node Using gcc for Syntax Checking 7112@subsection Using @command{gcc} for Syntax Checking 7113@table @option 7114@item -gnats 7115@cindex @option{-gnats} (@command{gcc}) 7116@ifclear vms 7117 7118@noindent 7119The @code{s} stands for ``syntax''. 7120@end ifclear 7121 7122Run GNAT in syntax checking only mode. For 7123example, the command 7124 7125@smallexample 7126$ gcc -c -gnats x.adb 7127@end smallexample 7128 7129@noindent 7130compiles file @file{x.adb} in syntax-check-only mode. You can check a 7131series of files in a single command 7132@ifclear vms 7133, and can use wild cards to specify such a group of files. 7134Note that you must specify the @option{-c} (compile 7135only) flag in addition to the @option{-gnats} flag. 7136@end ifclear 7137. 7138You may use other switches in conjunction with @option{-gnats}. In 7139particular, @option{-gnatl} and @option{-gnatv} are useful to control the 7140format of any generated error messages. 7141 7142When the source file is empty or contains only empty lines and/or comments, 7143the output is a warning: 7144 7145@smallexample 7146$ gcc -c -gnats -x ada toto.txt 7147toto.txt:1:01: warning: empty file, contains no compilation units 7148$ 7149@end smallexample 7150 7151Otherwise, the output is simply the error messages, if any. No object file or 7152ALI file is generated by a syntax-only compilation. Also, no units other 7153than the one specified are accessed. For example, if a unit @code{X} 7154@code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax 7155check only mode does not access the source file containing unit 7156@code{Y}. 7157 7158@cindex Multiple units, syntax checking 7159Normally, GNAT allows only a single unit in a source file. However, this 7160restriction does not apply in syntax-check-only mode, and it is possible 7161to check a file containing multiple compilation units concatenated 7162together. This is primarily used by the @code{gnatchop} utility 7163(@pxref{Renaming Files Using gnatchop}). 7164@end table 7165 7166@node Using gcc for Semantic Checking 7167@subsection Using @command{gcc} for Semantic Checking 7168@table @option 7169@item -gnatc 7170@cindex @option{-gnatc} (@command{gcc}) 7171 7172@ifclear vms 7173@noindent 7174The @code{c} stands for ``check''. 7175@end ifclear 7176Causes the compiler to operate in semantic check mode, 7177with full checking for all illegalities specified in the 7178Ada Reference Manual, but without generation of any object code 7179(no object file is generated). 7180 7181Because dependent files must be accessed, you must follow the GNAT 7182semantic restrictions on file structuring to operate in this mode: 7183 7184@itemize @bullet 7185@item 7186The needed source files must be accessible 7187(@pxref{Search Paths and the Run-Time Library (RTL)}). 7188 7189@item 7190Each file must contain only one compilation unit. 7191 7192@item 7193The file name and unit name must match (@pxref{File Naming Rules}). 7194@end itemize 7195 7196The output consists of error messages as appropriate. No object file is 7197generated. An @file{ALI} file is generated for use in the context of 7198cross-reference tools, but this file is marked as not being suitable 7199for binding (since no object file is generated). 7200The checking corresponds exactly to the notion of 7201legality in the Ada Reference Manual. 7202 7203Any unit can be compiled in semantics-checking-only mode, including 7204units that would not normally be compiled (subunits, 7205and specifications where a separate body is present). 7206@end table 7207 7208@node Compiling Different Versions of Ada 7209@subsection Compiling Different Versions of Ada 7210 7211@noindent 7212The switches described in this section allow you to explicitly specify 7213the version of the Ada language that your programs are written in. 7214By default @value{EDITION} assumes @value{DEFAULTLANGUAGEVERSION}, 7215but you can also specify @value{NONDEFAULTLANGUAGEVERSION} or 7216indicate Ada 83 compatibility mode. 7217 7218@table @option 7219@cindex Compatibility with Ada 83 7220 7221@item -gnat83 (Ada 83 Compatibility Mode) 7222@cindex @option{-gnat83} (@command{gcc}) 7223@cindex ACVC, Ada 83 tests 7224@cindex Ada 83 mode 7225 7226@noindent 7227Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch 7228specifies that the program is to be compiled in Ada 83 mode. With 7229@option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83 7230semantics where this can be done easily. 7231It is not possible to guarantee this switch does a perfect 7232job; some subtle tests, such as are 7233found in earlier ACVC tests (and that have been removed from the ACATS suite 7234for Ada 95), might not compile correctly. 7235Nevertheless, this switch may be useful in some circumstances, for example 7236where, due to contractual reasons, existing code needs to be maintained 7237using only Ada 83 features. 7238 7239With few exceptions (most notably the need to use @code{<>} on 7240@cindex Generic formal parameters 7241unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005 7242reserved words, and the use of packages 7243with optional bodies), it is not necessary to specify the 7244@option{-gnat83} switch when compiling Ada 83 programs, because, with rare 7245exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus 7246a correct Ada 83 program is usually also a correct program 7247in these later versions of the language standard. 7248For further information, please refer to @ref{Compatibility and Porting Guide}. 7249 7250@item -gnat95 (Ada 95 mode) 7251@cindex @option{-gnat95} (@command{gcc}) 7252@cindex Ada 95 mode 7253 7254@noindent 7255This switch directs the compiler to implement the Ada 95 version of the 7256language. 7257Since Ada 95 is almost completely upwards 7258compatible with Ada 83, Ada 83 programs may generally be compiled using 7259this switch (see the description of the @option{-gnat83} switch for further 7260information about Ada 83 mode). 7261If an Ada 2005 program is compiled in Ada 95 mode, 7262uses of the new Ada 2005 features will cause error 7263messages or warnings. 7264 7265This switch also can be used to cancel the effect of a previous 7266@option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012} 7267switch earlier in the command line. 7268 7269@item -gnat05 or -gnat2005 (Ada 2005 mode) 7270@cindex @option{-gnat05} (@command{gcc}) 7271@cindex @option{-gnat2005} (@command{gcc}) 7272@cindex Ada 2005 mode 7273 7274@noindent 7275This switch directs the compiler to implement the Ada 2005 version of the 7276language, as documented in the official Ada standards document. 7277Since Ada 2005 is almost completely upwards 7278compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs 7279may generally be compiled using this switch (see the description of the 7280@option{-gnat83} and @option{-gnat95} switches for further 7281information). 7282 7283@ifset PROEDITION 7284Note that even though Ada 2005 is the current official version of the 7285language, GNAT still compiles in Ada 95 mode by default, so if you are 7286using Ada 2005 features in your program, you must use this switch (or 7287the equivalent Ada_05 or Ada_2005 configuration pragmas). 7288@end ifset 7289 7290@item -gnat12 or -gnat2012 (Ada 2012 mode) 7291@cindex @option{-gnat12} (@command{gcc}) 7292@cindex @option{-gnat2012} (@command{gcc}) 7293@cindex Ada 2012 mode 7294 7295@noindent 7296This switch directs the compiler to implement the Ada 2012 version of the 7297language. 7298Since Ada 2012 is almost completely upwards 7299compatible with Ada 2005 (and thus also with Ada 83, and Ada 95), 7300Ada 83 and Ada 95 programs 7301may generally be compiled using this switch (see the description of the 7302@option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches 7303for further information). 7304 7305For information about the approved ``Ada Issues'' that have been incorporated 7306into Ada 2012, see @url{http://www.ada-auth.org/ais.html}. 7307Included with GNAT releases is a file @file{features-ada12} that describes 7308the set of implemented Ada 2012 features. 7309 7310@item -gnatX (Enable GNAT Extensions) 7311@cindex @option{-gnatX} (@command{gcc}) 7312@cindex Ada language extensions 7313@cindex GNAT extensions 7314 7315@noindent 7316This switch directs the compiler to implement the latest version of the 7317language (currently Ada 2012) and also to enable certain GNAT implementation 7318extensions that are not part of any Ada standard. For a full list of these 7319extensions, see the GNAT reference manual. 7320 7321@end table 7322 7323@node Character Set Control 7324@subsection Character Set Control 7325@table @option 7326@item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c} 7327@cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc}) 7328 7329@noindent 7330Normally GNAT recognizes the Latin-1 character set in source program 7331identifiers, as described in the Ada Reference Manual. 7332This switch causes 7333GNAT to recognize alternate character sets in identifiers. @var{c} is a 7334single character ^^or word^ indicating the character set, as follows: 7335 7336@table @code 7337@item 1 7338ISO 8859-1 (Latin-1) identifiers 7339 7340@item 2 7341ISO 8859-2 (Latin-2) letters allowed in identifiers 7342 7343@item 3 7344ISO 8859-3 (Latin-3) letters allowed in identifiers 7345 7346@item 4 7347ISO 8859-4 (Latin-4) letters allowed in identifiers 7348 7349@item 5 7350ISO 8859-5 (Cyrillic) letters allowed in identifiers 7351 7352@item 9 7353ISO 8859-15 (Latin-9) letters allowed in identifiers 7354 7355@item ^p^PC^ 7356IBM PC letters (code page 437) allowed in identifiers 7357 7358@item ^8^PC850^ 7359IBM PC letters (code page 850) allowed in identifiers 7360 7361@item ^f^FULL_UPPER^ 7362Full upper-half codes allowed in identifiers 7363 7364@item ^n^NO_UPPER^ 7365No upper-half codes allowed in identifiers 7366 7367@item ^w^WIDE^ 7368Wide-character codes (that is, codes greater than 255) 7369allowed in identifiers 7370@end table 7371 7372@xref{Foreign Language Representation}, for full details on the 7373implementation of these character sets. 7374 7375@item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e} 7376@cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc}) 7377Specify the method of encoding for wide characters. 7378@var{e} is one of the following: 7379 7380@table @code 7381 7382@item ^h^HEX^ 7383Hex encoding (brackets coding also recognized) 7384 7385@item ^u^UPPER^ 7386Upper half encoding (brackets encoding also recognized) 7387 7388@item ^s^SHIFT_JIS^ 7389Shift/JIS encoding (brackets encoding also recognized) 7390 7391@item ^e^EUC^ 7392EUC encoding (brackets encoding also recognized) 7393 7394@item ^8^UTF8^ 7395UTF-8 encoding (brackets encoding also recognized) 7396 7397@item ^b^BRACKETS^ 7398Brackets encoding only (default value) 7399@end table 7400For full details on these encoding 7401methods see @ref{Wide Character Encodings}. 7402Note that brackets coding is always accepted, even if one of the other 7403options is specified, so for example @option{-gnatW8} specifies that both 7404brackets and UTF-8 encodings will be recognized. The units that are 7405with'ed directly or indirectly will be scanned using the specified 7406representation scheme, and so if one of the non-brackets scheme is 7407used, it must be used consistently throughout the program. However, 7408since brackets encoding is always recognized, it may be conveniently 7409used in standard libraries, allowing these libraries to be used with 7410any of the available coding schemes. 7411 7412Note that brackets encoding only applies to program text. Within comments, 7413brackets are considered to be normal graphic characters, and bracket sequences 7414are never recognized as wide characters. 7415 7416If no @option{-gnatW?} parameter is present, then the default 7417representation is normally Brackets encoding only. However, if the 7418first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard 7419byte order mark or BOM for UTF-8), then these three characters are 7420skipped and the default representation for the file is set to UTF-8. 7421 7422Note that the wide character representation that is specified (explicitly 7423or by default) for the main program also acts as the default encoding used 7424for Wide_Text_IO files if not specifically overridden by a WCEM form 7425parameter. 7426 7427@end table 7428 7429When no @option{-gnatW?} is specified, then characters (other than wide 7430characters represented using brackets notation) are treated as 8-bit 7431Latin-1 codes. The codes recognized are the Latin-1 graphic characters, 7432and ASCII format effectors (CR, LF, HT, VT). Other lower half control 7433characters in the range 16#00#..16#1F# are not accepted in program text 7434or in comments. Upper half control characters (16#80#..16#9F#) are rejected 7435in program text, but allowed and ignored in comments. Note in particular 7436that the Next Line (NEL) character whose encoding is 16#85# is not recognized 7437as an end of line in this default mode. If your source program contains 7438instances of the NEL character used as a line terminator, 7439you must use UTF-8 encoding for the whole 7440source program. In default mode, all lines must be ended by a standard 7441end of line sequence (CR, CR/LF, or LF). 7442 7443Note that the convention of simply accepting all upper half characters in 7444comments means that programs that use standard ASCII for program text, but 7445UTF-8 encoding for comments are accepted in default mode, providing that the 7446comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator. 7447This is a common mode for many programs with foreign language comments. 7448 7449@node File Naming Control 7450@subsection File Naming Control 7451 7452@table @option 7453@item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n} 7454@cindex @option{-gnatk} (@command{gcc}) 7455Activates file name ``krunching''. @var{n}, a decimal integer in the range 74561-999, indicates the maximum allowable length of a file name (not 7457including the @file{.ads} or @file{.adb} extension). The default is not 7458to enable file name krunching. 7459 7460For the source file naming rules, @xref{File Naming Rules}. 7461@end table 7462 7463@node Subprogram Inlining Control 7464@subsection Subprogram Inlining Control 7465 7466@table @option 7467@c !sort! 7468@item -gnatn[12] 7469@cindex @option{-gnatn} (@command{gcc}) 7470@ifclear vms 7471The @code{n} here is intended to suggest the first syllable of the 7472word ``inline''. 7473@end ifclear 7474GNAT recognizes and processes @code{Inline} pragmas. However, for the 7475inlining to actually occur, optimization must be enabled and, in order 7476to enable inlining of subprograms specified by pragma @code{Inline}, 7477you must also specify this switch. 7478In the absence of this switch, GNAT does not attempt 7479inlining and does not need to access the bodies of 7480subprograms for which @code{pragma Inline} is specified if they are not 7481in the current unit. 7482 7483You can optionally specify the inlining level: 1 for moderate inlining across 7484modules, which is a good compromise between compilation times and performances 7485at run time, or 2 for full inlining across modules, which may bring about 7486longer compilation times. If no inlining level is specified, the compiler will 7487pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or 7488@option{-Os} and 2 for @option{-O3}. 7489 7490If you specify this switch the compiler will access these bodies, 7491creating an extra source dependency for the resulting object file, and 7492where possible, the call will be inlined. 7493For further details on when inlining is possible 7494see @ref{Inlining of Subprograms}. 7495 7496@item -gnatN 7497@cindex @option{-gnatN} (@command{gcc}) 7498This switch activates front-end inlining which also 7499generates additional dependencies. 7500 7501When using a gcc-based back end (in practice this means using any version 7502of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of 7503@option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred. 7504Historically front end inlining was more extensive than the gcc back end 7505inlining, but that is no longer the case. 7506@end table 7507 7508@node Auxiliary Output Control 7509@subsection Auxiliary Output Control 7510 7511@table @option 7512@item -gnatt 7513@cindex @option{-gnatt} (@command{gcc}) 7514@cindex Writing internal trees 7515@cindex Internal trees, writing to file 7516Causes GNAT to write the internal tree for a unit to a file (with the 7517extension @file{.adt}. 7518This not normally required, but is used by separate analysis tools. 7519Typically 7520these tools do the necessary compilations automatically, so you should 7521not have to specify this switch in normal operation. 7522Note that the combination of switches @option{-gnatct} 7523generates a tree in the form required by ASIS applications. 7524 7525@item -gnatu 7526@cindex @option{-gnatu} (@command{gcc}) 7527Print a list of units required by this compilation on @file{stdout}. 7528The listing includes all units on which the unit being compiled depends 7529either directly or indirectly. 7530 7531@ifclear vms 7532@item -pass-exit-codes 7533@cindex @option{-pass-exit-codes} (@command{gcc}) 7534If this switch is not used, the exit code returned by @command{gcc} when 7535compiling multiple files indicates whether all source files have 7536been successfully used to generate object files or not. 7537 7538When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended 7539exit status and allows an integrated development environment to better 7540react to a compilation failure. Those exit status are: 7541 7542@table @asis 7543@item 5 7544There was an error in at least one source file. 7545@item 3 7546At least one source file did not generate an object file. 7547@item 2 7548The compiler died unexpectedly (internal error for example). 7549@item 0 7550An object file has been generated for every source file. 7551@end table 7552@end ifclear 7553@end table 7554 7555@node Debugging Control 7556@subsection Debugging Control 7557 7558@table @option 7559@c !sort! 7560@cindex Debugging options 7561@ifclear vms 7562@item -gnatd@var{x} 7563@cindex @option{-gnatd} (@command{gcc}) 7564Activate internal debugging switches. @var{x} is a letter or digit, or 7565string of letters or digits, which specifies the type of debugging 7566outputs desired. Normally these are used only for internal development 7567or system debugging purposes. You can find full documentation for these 7568switches in the body of the @code{Debug} unit in the compiler source 7569file @file{debug.adb}. 7570@end ifclear 7571 7572@item -gnatG[=nn] 7573@cindex @option{-gnatG} (@command{gcc}) 7574This switch causes the compiler to generate auxiliary output containing 7575a pseudo-source listing of the generated expanded code. Like most Ada 7576compilers, GNAT works by first transforming the high level Ada code into 7577lower level constructs. For example, tasking operations are transformed 7578into calls to the tasking run-time routines. A unique capability of GNAT 7579is to list this expanded code in a form very close to normal Ada source. 7580This is very useful in understanding the implications of various Ada 7581usage on the efficiency of the generated code. There are many cases in 7582Ada (e.g.@: the use of controlled types), where simple Ada statements can 7583generate a lot of run-time code. By using @option{-gnatG} you can identify 7584these cases, and consider whether it may be desirable to modify the coding 7585approach to improve efficiency. 7586 7587The optional parameter @code{nn} if present after -gnatG specifies an 7588alternative maximum line length that overrides the normal default of 72. 7589This value is in the range 40-999999, values less than 40 being silently 7590reset to 40. The equal sign is optional. 7591 7592The format of the output is very similar to standard Ada source, and is 7593easily understood by an Ada programmer. The following special syntactic 7594additions correspond to low level features used in the generated code that 7595do not have any exact analogies in pure Ada source form. The following 7596is a partial list of these special constructions. See the spec 7597of package @code{Sprint} in file @file{sprint.ads} for a full list. 7598 7599If the switch @option{-gnatL} is used in conjunction with 7600@cindex @option{-gnatL} (@command{gcc}) 7601@option{-gnatG}, then the original source lines are interspersed 7602in the expanded source (as comment lines with the original line number). 7603 7604@table @code 7605@item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]} 7606Shows the storage pool being used for an allocator. 7607 7608@item at end @var{procedure-name}; 7609Shows the finalization (cleanup) procedure for a scope. 7610 7611@item (if @var{expr} then @var{expr} else @var{expr}) 7612Conditional expression equivalent to the @code{x?y:z} construction in C. 7613 7614@item @var{target}^^^(@var{source}) 7615A conversion with floating-point truncation instead of rounding. 7616 7617@item @var{target}?(@var{source}) 7618A conversion that bypasses normal Ada semantic checking. In particular 7619enumeration types and fixed-point types are treated simply as integers. 7620 7621@item @var{target}?^^^(@var{source}) 7622Combines the above two cases. 7623 7624@item @var{x} #/ @var{y} 7625@itemx @var{x} #mod @var{y} 7626@itemx @var{x} #* @var{y} 7627@itemx @var{x} #rem @var{y} 7628A division or multiplication of fixed-point values which are treated as 7629integers without any kind of scaling. 7630 7631@item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]} 7632Shows the storage pool associated with a @code{free} statement. 7633 7634@item [subtype or type declaration] 7635Used to list an equivalent declaration for an internally generated 7636type that is referenced elsewhere in the listing. 7637 7638@c @item freeze @var{type-name} @ovar{actions} 7639@c Expanding @ovar macro inline (explanation in macro def comments) 7640@item freeze @var{type-name} @r{[}@var{actions}@r{]} 7641Shows the point at which @var{type-name} is frozen, with possible 7642associated actions to be performed at the freeze point. 7643 7644@item reference @var{itype} 7645Reference (and hence definition) to internal type @var{itype}. 7646 7647@item @var{function-name}! (@var{arg}, @var{arg}, @var{arg}) 7648Intrinsic function call. 7649 7650@item @var{label-name} : label 7651Declaration of label @var{labelname}. 7652 7653@item #$ @var{subprogram-name} 7654An implicit call to a run-time support routine 7655(to meet the requirement of H.3.1(9) in a 7656convenient manner). 7657 7658@item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr} 7659A multiple concatenation (same effect as @var{expr} & @var{expr} & 7660@var{expr}, but handled more efficiently). 7661 7662@item [constraint_error] 7663Raise the @code{Constraint_Error} exception. 7664 7665@item @var{expression}'reference 7666A pointer to the result of evaluating @var{expression}. 7667 7668@item @var{target-type}!(@var{source-expression}) 7669An unchecked conversion of @var{source-expression} to @var{target-type}. 7670 7671@item [@var{numerator}/@var{denominator}] 7672Used to represent internal real literals (that) have no exact 7673representation in base 2-16 (for example, the result of compile time 7674evaluation of the expression 1.0/27.0). 7675@end table 7676 7677@item -gnatD[=nn] 7678@cindex @option{-gnatD} (@command{gcc}) 7679When used in conjunction with @option{-gnatG}, this switch causes 7680the expanded source, as described above for 7681@option{-gnatG} to be written to files with names 7682@file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name, 7683instead of to the standard output file. For 7684example, if the source file name is @file{hello.adb}, then a file 7685@file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging 7686information generated by the @command{gcc} @option{^-g^/DEBUG^} switch 7687will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows 7688you to do source level debugging using the generated code which is 7689sometimes useful for complex code, for example to find out exactly 7690which part of a complex construction raised an exception. This switch 7691also suppress generation of cross-reference information (see 7692@option{-gnatx}) since otherwise the cross-reference information 7693would refer to the @file{^.dg^.DG^} file, which would cause 7694confusion since this is not the original source file. 7695 7696Note that @option{-gnatD} actually implies @option{-gnatG} 7697automatically, so it is not necessary to give both options. 7698In other words @option{-gnatD} is equivalent to @option{-gnatDG}). 7699 7700If the switch @option{-gnatL} is used in conjunction with 7701@cindex @option{-gnatL} (@command{gcc}) 7702@option{-gnatDG}, then the original source lines are interspersed 7703in the expanded source (as comment lines with the original line number). 7704 7705The optional parameter @code{nn} if present after -gnatD specifies an 7706alternative maximum line length that overrides the normal default of 72. 7707This value is in the range 40-999999, values less than 40 being silently 7708reset to 40. The equal sign is optional. 7709 7710@item -gnatr 7711@cindex @option{-gnatr} (@command{gcc}) 7712@cindex pragma Restrictions 7713This switch causes pragma Restrictions to be treated as Restriction_Warnings 7714so that violation of restrictions causes warnings rather than illegalities. 7715This is useful during the development process when new restrictions are added 7716or investigated. The switch also causes pragma Profile to be treated as 7717Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set 7718restriction warnings rather than restrictions. 7719 7720@ifclear vms 7721@item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]} 7722@cindex @option{-gnatR} (@command{gcc}) 7723This switch controls output from the compiler of a listing showing 7724representation information for declared types and objects. For 7725@option{-gnatR0}, no information is output (equivalent to omitting 7726the @option{-gnatR} switch). For @option{-gnatR1} (which is the default, 7727so @option{-gnatR} with no parameter has the same effect), size and alignment 7728information is listed for declared array and record types. For 7729@option{-gnatR2}, size and alignment information is listed for all 7730declared types and objects. Finally @option{-gnatR3} includes symbolic 7731expressions for values that are computed at run time for 7732variant records. These symbolic expressions have a mostly obvious 7733format with #n being used to represent the value of the n'th 7734discriminant. See source files @file{repinfo.ads/adb} in the 7735@code{GNAT} sources for full details on the format of @option{-gnatR3} 7736output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then 7737the output is to a file with the name @file{^file.rep^file_REP^} where 7738file is the name of the corresponding source file. 7739@end ifclear 7740@ifset vms 7741@item /REPRESENTATION_INFO 7742@cindex @option{/REPRESENTATION_INFO} (@command{gcc}) 7743This qualifier controls output from the compiler of a listing showing 7744representation information for declared types and objects. For 7745@option{/REPRESENTATION_INFO=NONE}, no information is output 7746(equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier). 7747@option{/REPRESENTATION_INFO} without option is equivalent to 7748@option{/REPRESENTATION_INFO=ARRAYS}. 7749For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment 7750information is listed for declared array and record types. For 7751@option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information 7752is listed for all expression information for values that are computed 7753at run time for variant records. These symbolic expressions have a mostly 7754obvious format with #n being used to represent the value of the n'th 7755discriminant. See source files @file{REPINFO.ADS/ADB} in the 7756@code{GNAT} sources for full details on the format of 7757@option{/REPRESENTATION_INFO=SYMBOLIC} output. 7758If _FILE is added at the end of an option 7759(e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}), 7760then the output is to a file with the name @file{file_REP} where 7761file is the name of the corresponding source file. 7762@end ifset 7763Note that it is possible for record components to have zero size. In 7764this case, the component clause uses an obvious extension of permitted 7765Ada syntax, for example @code{at 0 range 0 .. -1}. 7766 7767Representation information requires that code be generated (since it is the 7768code generator that lays out complex data structures). If an attempt is made 7769to output representation information when no code is generated, for example 7770when a subunit is compiled on its own, then no information can be generated 7771and the compiler outputs a message to this effect. 7772 7773@item -gnatS 7774@cindex @option{-gnatS} (@command{gcc}) 7775The use of the switch @option{-gnatS} for an 7776Ada compilation will cause the compiler to output a 7777representation of package Standard in a form very 7778close to standard Ada. It is not quite possible to 7779do this entirely in standard Ada (since new 7780numeric base types cannot be created in standard 7781Ada), but the output is easily 7782readable to any Ada programmer, and is useful to 7783determine the characteristics of target dependent 7784types in package Standard. 7785 7786@item -gnatx 7787@cindex @option{-gnatx} (@command{gcc}) 7788Normally the compiler generates full cross-referencing information in 7789the @file{ALI} file. This information is used by a number of tools, 7790including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch 7791suppresses this information. This saves some space and may slightly 7792speed up compilation, but means that these tools cannot be used. 7793@end table 7794 7795@node Exception Handling Control 7796@subsection Exception Handling Control 7797 7798@noindent 7799GNAT uses two methods for handling exceptions at run-time. The 7800@code{setjmp/longjmp} method saves the context when entering 7801a frame with an exception handler. Then when an exception is 7802raised, the context can be restored immediately, without the 7803need for tracing stack frames. This method provides very fast 7804exception propagation, but introduces significant overhead for 7805the use of exception handlers, even if no exception is raised. 7806 7807The other approach is called ``zero cost'' exception handling. 7808With this method, the compiler builds static tables to describe 7809the exception ranges. No dynamic code is required when entering 7810a frame containing an exception handler. When an exception is 7811raised, the tables are used to control a back trace of the 7812subprogram invocation stack to locate the required exception 7813handler. This method has considerably poorer performance for 7814the propagation of exceptions, but there is no overhead for 7815exception handlers if no exception is raised. Note that in this 7816mode and in the context of mixed Ada and C/C++ programming, 7817to propagate an exception through a C/C++ code, the C/C++ code 7818must be compiled with the @option{-funwind-tables} GCC's 7819option. 7820 7821The following switches may be used to control which of the 7822two exception handling methods is used. 7823 7824@table @option 7825@c !sort! 7826 7827@item --RTS=sjlj 7828@cindex @option{--RTS=sjlj} (@command{gnatmake}) 7829This switch causes the setjmp/longjmp run-time (when available) to be used 7830for exception handling. If the default 7831mechanism for the target is zero cost exceptions, then 7832this switch can be used to modify this default, and must be 7833used for all units in the partition. 7834This option is rarely used. One case in which it may be 7835advantageous is if you have an application where exception 7836raising is common and the overall performance of the 7837application is improved by favoring exception propagation. 7838 7839@item --RTS=zcx 7840@cindex @option{--RTS=zcx} (@command{gnatmake}) 7841@cindex Zero Cost Exceptions 7842This switch causes the zero cost approach to be used 7843for exception handling. If this is the default mechanism for the 7844target (see below), then this switch is unneeded. If the default 7845mechanism for the target is setjmp/longjmp exceptions, then 7846this switch can be used to modify this default, and must be 7847used for all units in the partition. 7848This option can only be used if the zero cost approach 7849is available for the target in use, otherwise it will generate an error. 7850@end table 7851 7852@noindent 7853The same option @option{--RTS} must be used both for @command{gcc} 7854and @command{gnatbind}. Passing this option to @command{gnatmake} 7855(@pxref{Switches for gnatmake}) will ensure the required consistency 7856through the compilation and binding steps. 7857 7858@node Units to Sources Mapping Files 7859@subsection Units to Sources Mapping Files 7860 7861@table @option 7862 7863@item -gnatem=@var{path} 7864@cindex @option{-gnatem} (@command{gcc}) 7865A mapping file is a way to communicate to the compiler two mappings: 7866from unit names to file names (without any directory information) and from 7867file names to path names (with full directory information). These mappings 7868are used by the compiler to short-circuit the path search. 7869 7870The use of mapping files is not required for correct operation of the 7871compiler, but mapping files can improve efficiency, particularly when 7872sources are read over a slow network connection. In normal operation, 7873you need not be concerned with the format or use of mapping files, 7874and the @option{-gnatem} switch is not a switch that you would use 7875explicitly. It is intended primarily for use by automatic tools such as 7876@command{gnatmake} running under the project file facility. The 7877description here of the format of mapping files is provided 7878for completeness and for possible use by other tools. 7879 7880A mapping file is a sequence of sets of three lines. In each set, the 7881first line is the unit name, in lower case, with @code{%s} appended 7882for specs and @code{%b} appended for bodies; the second line is the 7883file name; and the third line is the path name. 7884 7885Example: 7886@smallexample 7887 main%b 7888 main.2.ada 7889 /gnat/project1/sources/main.2.ada 7890@end smallexample 7891 7892When the switch @option{-gnatem} is specified, the compiler will 7893create in memory the two mappings from the specified file. If there is 7894any problem (nonexistent file, truncated file or duplicate entries), 7895no mapping will be created. 7896 7897Several @option{-gnatem} switches may be specified; however, only the 7898last one on the command line will be taken into account. 7899 7900When using a project file, @command{gnatmake} creates a temporary 7901mapping file and communicates it to the compiler using this switch. 7902 7903@end table 7904 7905@node Integrated Preprocessing 7906@subsection Integrated Preprocessing 7907 7908@noindent 7909GNAT sources may be preprocessed immediately before compilation. 7910In this case, the actual 7911text of the source is not the text of the source file, but is derived from it 7912through a process called preprocessing. Integrated preprocessing is specified 7913through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep} 7914indicates, through a text file, the preprocessing data to be used. 7915@option{-gnateD} specifies or modifies the values of preprocessing symbol. 7916 7917@noindent 7918Note that when integrated preprocessing is used, the output from the 7919preprocessor is not written to any external file. Instead it is passed 7920internally to the compiler. If you need to preserve the result of 7921preprocessing in a file, then you should use @command{gnatprep} 7922to perform the desired preprocessing in stand-alone mode. 7923 7924@noindent 7925It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be 7926used when Integrated Preprocessing is used. The reason is that preprocessing 7927with another Preprocessing Data file without changing the sources will 7928not trigger recompilation without this switch. 7929 7930@noindent 7931Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost 7932always trigger recompilation for sources that are preprocessed, 7933because @command{gnatmake} cannot compute the checksum of the source after 7934preprocessing. 7935 7936@noindent 7937The actual preprocessing function is described in details in section 7938@ref{Preprocessing Using gnatprep}. This section only describes how integrated 7939preprocessing is triggered and parameterized. 7940 7941@table @code 7942 7943@item -gnatep=@var{file} 7944@cindex @option{-gnatep} (@command{gcc}) 7945This switch indicates to the compiler the file name (without directory 7946information) of the preprocessor data file to use. The preprocessor data file 7947should be found in the source directories. Note that when the compiler is 7948called by a builder (@command{gnatmake} or @command{gprbuild}) with a project 7949file, if the object directory is not also a source directory, the builder needs 7950to be called with @option{-x}. 7951 7952@noindent 7953A preprocessing data file is a text file with significant lines indicating 7954how should be preprocessed either a specific source or all sources not 7955mentioned in other lines. A significant line is a nonempty, non-comment line. 7956Comments are similar to Ada comments. 7957 7958@noindent 7959Each significant line starts with either a literal string or the character '*'. 7960A literal string is the file name (without directory information) of the source 7961to preprocess. A character '*' indicates the preprocessing for all the sources 7962that are not specified explicitly on other lines (order of the lines is not 7963significant). It is an error to have two lines with the same file name or two 7964lines starting with the character '*'. 7965 7966@noindent 7967After the file name or the character '*', another optional literal string 7968indicating the file name of the definition file to be used for preprocessing 7969(@pxref{Form of Definitions File}). The definition files are found by the 7970compiler in one of the source directories. In some cases, when compiling 7971a source in a directory other than the current directory, if the definition 7972file is in the current directory, it may be necessary to add the current 7973directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise 7974the compiler would not find the definition file. 7975 7976@noindent 7977Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may 7978be found. Those ^switches^switches^ are: 7979 7980@table @code 7981 7982@item -b 7983Causes both preprocessor lines and the lines deleted by 7984preprocessing to be replaced by blank lines, preserving the line number. 7985This ^switch^switch^ is always implied; however, if specified after @option{-c} 7986it cancels the effect of @option{-c}. 7987 7988@item -c 7989Causes both preprocessor lines and the lines deleted 7990by preprocessing to be retained as comments marked 7991with the special string ``@code{--! }''. 7992 7993@item -Dsymbol=value 7994Define or redefine a symbol, associated with value. A symbol is an Ada 7995identifier, or an Ada reserved word, with the exception of @code{if}, 7996@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}. 7997@code{value} is either a literal string, an Ada identifier or any Ada reserved 7998word. A symbol declared with this ^switch^switch^ replaces a symbol with the 7999same name defined in a definition file. 8000 8001@item -s 8002Causes a sorted list of symbol names and values to be 8003listed on the standard output file. 8004 8005@item -u 8006Causes undefined symbols to be treated as having the value @code{FALSE} 8007in the context 8008of a preprocessor test. In the absence of this option, an undefined symbol in 8009a @code{#if} or @code{#elsif} test will be treated as an error. 8010 8011@end table 8012 8013@noindent 8014Examples of valid lines in a preprocessor data file: 8015 8016@smallexample 8017 "toto.adb" "prep.def" -u 8018 -- preprocess "toto.adb", using definition file "prep.def", 8019 -- undefined symbol are False. 8020 8021 * -c -DVERSION=V101 8022 -- preprocess all other sources without a definition file; 8023 -- suppressed lined are commented; symbol VERSION has the value V101. 8024 8025 "titi.adb" "prep2.def" -s 8026 -- preprocess "titi.adb", using definition file "prep2.def"; 8027 -- list all symbols with their values. 8028@end smallexample 8029 8030@item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]} 8031@cindex @option{-gnateD} (@command{gcc}) 8032Define or redefine a preprocessing symbol, associated with value. If no value 8033is given on the command line, then the value of the symbol is @code{True}. 8034A symbol is an identifier, following normal Ada (case-insensitive) 8035rules for its syntax, and value is any sequence (including an empty sequence) 8036of characters from the set (letters, digits, period, underline). 8037Ada reserved words may be used as symbols, with the exceptions of @code{if}, 8038@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}. 8039 8040@noindent 8041A symbol declared with this ^switch^switch^ on the command line replaces a 8042symbol with the same name either in a definition file or specified with a 8043^switch^switch^ -D in the preprocessor data file. 8044 8045@noindent 8046This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}. 8047 8048@item -gnateG 8049When integrated preprocessing is performed and the preprocessor modifies 8050the source text, write the result of this preprocessing into a file 8051<source>^.prep^_prep^. 8052 8053@end table 8054 8055@node Code Generation Control 8056@subsection Code Generation Control 8057 8058@noindent 8059 8060The GCC technology provides a wide range of target dependent 8061@option{-m} switches for controlling 8062details of code generation with respect to different versions of 8063architectures. This includes variations in instruction sets (e.g.@: 8064different members of the power pc family), and different requirements 8065for optimal arrangement of instructions (e.g.@: different members of 8066the x86 family). The list of available @option{-m} switches may be 8067found in the GCC documentation. 8068 8069Use of these @option{-m} switches may in some cases result in improved 8070code performance. 8071 8072The @value{EDITION} technology is tested and qualified without any 8073@option{-m} switches, 8074so generally the most reliable approach is to avoid the use of these 8075switches. However, we generally expect most of these switches to work 8076successfully with @value{EDITION}, and many customers have reported successful 8077use of these options. 8078 8079Our general advice is to avoid the use of @option{-m} switches unless 8080special needs lead to requirements in this area. In particular, 8081there is no point in using @option{-m} switches to improve performance 8082unless you actually see a performance improvement. 8083 8084@ifset vms 8085@node Return Codes 8086@subsection Return Codes 8087@cindex Return Codes 8088@cindex @option{/RETURN_CODES=VMS} 8089 8090@noindent 8091On VMS, GNAT compiled programs return POSIX-style codes by default, 8092e.g.@: @option{/RETURN_CODES=POSIX}. 8093 8094To enable VMS style return codes, use GNAT BIND and LINK with the option 8095@option{/RETURN_CODES=VMS}. For example: 8096 8097@smallexample 8098GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS 8099GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS 8100@end smallexample 8101 8102@noindent 8103Programs built with /RETURN_CODES=VMS are suitable to be called in 8104VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX 8105are suitable for spawning with appropriate GNAT RTL routines. 8106 8107@end ifset 8108 8109@node Search Paths and the Run-Time Library (RTL) 8110@section Search Paths and the Run-Time Library (RTL) 8111 8112@noindent 8113With the GNAT source-based library system, the compiler must be able to 8114find source files for units that are needed by the unit being compiled. 8115Search paths are used to guide this process. 8116 8117The compiler compiles one source file whose name must be given 8118explicitly on the command line. In other words, no searching is done 8119for this file. To find all other source files that are needed (the most 8120common being the specs of units), the compiler examines the following 8121directories, in the following order: 8122 8123@enumerate 8124@item 8125The directory containing the source file of the main unit being compiled 8126(the file name on the command line). 8127 8128@item 8129Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the 8130@command{gcc} command line, in the order given. 8131 8132@item 8133@findex ADA_PRJ_INCLUDE_FILE 8134Each of the directories listed in the text file whose name is given 8135by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^. 8136 8137@noindent 8138@env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^ 8139driver when project files are used. It should not normally be set 8140by other means. 8141 8142@item 8143@findex ADA_INCLUDE_PATH 8144Each of the directories listed in the value of the 8145@env{ADA_INCLUDE_PATH} ^environment variable^logical name^. 8146@ifclear vms 8147Construct this value 8148exactly as the @env{PATH} environment variable: a list of directory 8149names separated by colons (semicolons when working with the NT version). 8150@end ifclear 8151@ifset vms 8152Normally, define this value as a logical name containing a comma separated 8153list of directory names. 8154 8155This variable can also be defined by means of an environment string 8156(an argument to the HP C exec* set of functions). 8157 8158Logical Name: 8159@smallexample 8160DEFINE ANOTHER_PATH FOO:[BAG] 8161DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] 8162@end smallexample 8163 8164By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] 8165first, followed by the standard Ada 8166libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE]. 8167If this is not redefined, the user will obtain the HP Ada 83 IO packages 8168(Text_IO, Sequential_IO, etc) 8169instead of the standard Ada packages. Thus, in order to get the standard Ada 8170packages by default, ADA_INCLUDE_PATH must be redefined. 8171@end ifset 8172 8173@item 8174The content of the @file{ada_source_path} file which is part of the GNAT 8175installation tree and is used to store standard libraries such as the 8176GNAT Run Time Library (RTL) source files. 8177@ifclear vms 8178@ref{Installing a library} 8179@end ifclear 8180@end enumerate 8181 8182@noindent 8183Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^} 8184inhibits the use of the directory 8185containing the source file named in the command line. You can still 8186have this directory on your search path, but in this case it must be 8187explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch. 8188 8189Specifying the switch @option{-nostdinc} 8190inhibits the search of the default location for the GNAT Run Time 8191Library (RTL) source files. 8192 8193The compiler outputs its object files and ALI files in the current 8194working directory. 8195@ifclear vms 8196Caution: The object file can be redirected with the @option{-o} switch; 8197however, @command{gcc} and @code{gnat1} have not been coordinated on this 8198so the @file{ALI} file will not go to the right place. Therefore, you should 8199avoid using the @option{-o} switch. 8200@end ifclear 8201 8202@findex System.IO 8203The packages @code{Ada}, @code{System}, and @code{Interfaces} and their 8204children make up the GNAT RTL, together with the simple @code{System.IO} 8205package used in the @code{"Hello World"} example. The sources for these units 8206are needed by the compiler and are kept together in one directory. Not 8207all of the bodies are needed, but all of the sources are kept together 8208anyway. In a normal installation, you need not specify these directory 8209names when compiling or binding. Either the environment variables or 8210the built-in defaults cause these files to be found. 8211 8212In addition to the language-defined hierarchies (@code{System}, @code{Ada} and 8213@code{Interfaces}), the GNAT distribution provides a fourth hierarchy, 8214consisting of child units of @code{GNAT}. This is a collection of generally 8215useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About 8216This Guid, gnat_rm, GNAT Reference Manual}, for further details. 8217 8218Besides simplifying access to the RTL, a major use of search paths is 8219in compiling sources from multiple directories. This can make 8220development environments much more flexible. 8221 8222@node Order of Compilation Issues 8223@section Order of Compilation Issues 8224 8225@noindent 8226If, in our earlier example, there was a spec for the @code{hello} 8227procedure, it would be contained in the file @file{hello.ads}; yet this 8228file would not have to be explicitly compiled. This is the result of the 8229model we chose to implement library management. Some of the consequences 8230of this model are as follows: 8231 8232@itemize @bullet 8233@item 8234There is no point in compiling specs (except for package 8235specs with no bodies) because these are compiled as needed by clients. If 8236you attempt a useless compilation, you will receive an error message. 8237It is also useless to compile subunits because they are compiled as needed 8238by the parent. 8239 8240@item 8241There are no order of compilation requirements: performing a 8242compilation never obsoletes anything. The only way you can obsolete 8243something and require recompilations is to modify one of the 8244source files on which it depends. 8245 8246@item 8247There is no library as such, apart from the ALI files 8248(@pxref{The Ada Library Information Files}, for information on the format 8249of these files). For now we find it convenient to create separate ALI files, 8250but eventually the information therein may be incorporated into the object 8251file directly. 8252 8253@item 8254When you compile a unit, the source files for the specs of all units 8255that it @code{with}'s, all its subunits, and the bodies of any generics it 8256instantiates must be available (reachable by the search-paths mechanism 8257described above), or you will receive a fatal error message. 8258@end itemize 8259 8260@node Examples 8261@section Examples 8262 8263@noindent 8264The following are some typical Ada compilation command line examples: 8265 8266@table @code 8267@item $ gcc -c xyz.adb 8268Compile body in file @file{xyz.adb} with all default options. 8269 8270@ifclear vms 8271@item $ gcc -c -O2 -gnata xyz-def.adb 8272@end ifclear 8273@ifset vms 8274@item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb 8275@end ifset 8276 8277Compile the child unit package in file @file{xyz-def.adb} with extensive 8278optimizations, and pragma @code{Assert}/@code{Debug} statements 8279enabled. 8280 8281@item $ gcc -c -gnatc abc-def.adb 8282Compile the subunit in file @file{abc-def.adb} in semantic-checking-only 8283mode. 8284@end table 8285 8286@node Binding Using gnatbind 8287@chapter Binding Using @code{gnatbind} 8288@findex gnatbind 8289 8290@menu 8291* Running gnatbind:: 8292* Switches for gnatbind:: 8293* Command-Line Access:: 8294* Search Paths for gnatbind:: 8295* Examples of gnatbind Usage:: 8296@end menu 8297 8298@noindent 8299This chapter describes the GNAT binder, @code{gnatbind}, which is used 8300to bind compiled GNAT objects. 8301 8302Note: to invoke @code{gnatbind} with a project file, use the @code{gnat} 8303driver (see @ref{The GNAT Driver and Project Files}). 8304 8305The @code{gnatbind} program performs four separate functions: 8306 8307@enumerate 8308@item 8309Checks that a program is consistent, in accordance with the rules in 8310Chapter 10 of the Ada Reference Manual. In particular, error 8311messages are generated if a program uses inconsistent versions of a 8312given unit. 8313 8314@item 8315Checks that an acceptable order of elaboration exists for the program 8316and issues an error message if it cannot find an order of elaboration 8317that satisfies the rules in Chapter 10 of the Ada Language Manual. 8318 8319@item 8320Generates a main program incorporating the given elaboration order. 8321This program is a small Ada package (body and spec) that 8322must be subsequently compiled 8323using the GNAT compiler. The necessary compilation step is usually 8324performed automatically by @command{gnatlink}. The two most important 8325functions of this program 8326are to call the elaboration routines of units in an appropriate order 8327and to call the main program. 8328 8329@item 8330Determines the set of object files required by the given main program. 8331This information is output in the forms of comments in the generated program, 8332to be read by the @command{gnatlink} utility used to link the Ada application. 8333@end enumerate 8334 8335@node Running gnatbind 8336@section Running @code{gnatbind} 8337 8338@noindent 8339The form of the @code{gnatbind} command is 8340 8341@smallexample 8342@c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches} 8343@c Expanding @ovar macro inline (explanation in macro def comments) 8344$ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]} 8345@end smallexample 8346 8347@noindent 8348where @file{@var{mainprog}.adb} is the Ada file containing the main program 8349unit body. @code{gnatbind} constructs an Ada 8350package in two files whose names are 8351@file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}. 8352For example, if given the 8353parameter @file{hello.ali}, for a main program contained in file 8354@file{hello.adb}, the binder output files would be @file{b~hello.ads} 8355and @file{b~hello.adb}. 8356 8357When doing consistency checking, the binder takes into consideration 8358any source files it can locate. For example, if the binder determines 8359that the given main program requires the package @code{Pack}, whose 8360@file{.ALI} 8361file is @file{pack.ali} and whose corresponding source spec file is 8362@file{pack.ads}, it attempts to locate the source file @file{pack.ads} 8363(using the same search path conventions as previously described for the 8364@command{gcc} command). If it can locate this source file, it checks that 8365the time stamps 8366or source checksums of the source and its references to in @file{ALI} files 8367match. In other words, any @file{ALI} files that mentions this spec must have 8368resulted from compiling this version of the source file (or in the case 8369where the source checksums match, a version close enough that the 8370difference does not matter). 8371 8372@cindex Source files, use by binder 8373The effect of this consistency checking, which includes source files, is 8374that the binder ensures that the program is consistent with the latest 8375version of the source files that can be located at bind time. Editing a 8376source file without compiling files that depend on the source file cause 8377error messages to be generated by the binder. 8378 8379For example, suppose you have a main program @file{hello.adb} and a 8380package @code{P}, from file @file{p.ads} and you perform the following 8381steps: 8382 8383@enumerate 8384@item 8385Enter @code{gcc -c hello.adb} to compile the main program. 8386 8387@item 8388Enter @code{gcc -c p.ads} to compile package @code{P}. 8389 8390@item 8391Edit file @file{p.ads}. 8392 8393@item 8394Enter @code{gnatbind hello}. 8395@end enumerate 8396 8397@noindent 8398At this point, the file @file{p.ali} contains an out-of-date time stamp 8399because the file @file{p.ads} has been edited. The attempt at binding 8400fails, and the binder generates the following error messages: 8401 8402@smallexample 8403error: "hello.adb" must be recompiled ("p.ads" has been modified) 8404error: "p.ads" has been modified and must be recompiled 8405@end smallexample 8406 8407@noindent 8408Now both files must be recompiled as indicated, and then the bind can 8409succeed, generating a main program. You need not normally be concerned 8410with the contents of this file, but for reference purposes a sample 8411binder output file is given in @ref{Example of Binder Output File}. 8412 8413In most normal usage, the default mode of @command{gnatbind} which is to 8414generate the main package in Ada, as described in the previous section. 8415In particular, this means that any Ada programmer can read and understand 8416the generated main program. It can also be debugged just like any other 8417Ada code provided the @option{^-g^/DEBUG^} switch is used for 8418@command{gnatbind} and @command{gnatlink}. 8419 8420@node Switches for gnatbind 8421@section Switches for @command{gnatbind} 8422 8423@noindent 8424The following switches are available with @code{gnatbind}; details will 8425be presented in subsequent sections. 8426 8427@menu 8428* Consistency-Checking Modes:: 8429* Binder Error Message Control:: 8430* Elaboration Control:: 8431* Output Control:: 8432* Dynamic Allocation Control:: 8433* Binding with Non-Ada Main Programs:: 8434* Binding Programs with No Main Subprogram:: 8435@end menu 8436 8437@table @option 8438@c !sort! 8439 8440@item --version 8441@cindex @option{--version} @command{gnatbind} 8442Display Copyright and version, then exit disregarding all other options. 8443 8444@item --help 8445@cindex @option{--help} @command{gnatbind} 8446If @option{--version} was not used, display usage, then exit disregarding 8447all other options. 8448 8449@item -a 8450@cindex @option{-a} @command{gnatbind} 8451Indicates that, if supported by the platform, the adainit procedure should 8452be treated as an initialisation routine by the linker (a constructor). This 8453is intended to be used by the Project Manager to automatically initialize 8454shared Stand-Alone Libraries. 8455 8456@item ^-aO^/OBJECT_SEARCH^ 8457@cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind}) 8458Specify directory to be searched for ALI files. 8459 8460@item ^-aI^/SOURCE_SEARCH^ 8461@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind}) 8462Specify directory to be searched for source file. 8463 8464@item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]} 8465@cindex @option{^-A^/ALI_LIST^} (@command{gnatbind}) 8466Output ALI list (to standard output or to the named file). 8467 8468@item ^-b^/REPORT_ERRORS=BRIEF^ 8469@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind}) 8470Generate brief messages to @file{stderr} even if verbose mode set. 8471 8472@item ^-c^/NOOUTPUT^ 8473@cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind}) 8474Check only, no generation of binder output file. 8475 8476@item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]} 8477@cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind}) 8478This switch can be used to change the default task stack size value 8479to a specified size @var{nn}, which is expressed in bytes by default, or 8480in kilobytes when suffixed with @var{k} or in megabytes when suffixed 8481with @var{m}. 8482In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent, 8483in effect, to completing all task specs with 8484@smallexample @c ada 8485 pragma Storage_Size (nn); 8486@end smallexample 8487When they do not already have such a pragma. 8488 8489@item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]} 8490@cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind}) 8491This switch can be used to change the default secondary stack size value 8492to a specified size @var{nn}, which is expressed in bytes by default, or 8493in kilobytes when suffixed with @var{k} or in megabytes when suffixed 8494with @var{m}. 8495 8496The secondary stack is used to deal with functions that return a variable 8497sized result, for example a function returning an unconstrained 8498String. There are two ways in which this secondary stack is allocated. 8499 8500For most targets, the secondary stack is growing on demand and is allocated 8501as a chain of blocks in the heap. The -D option is not very 8502relevant. It only give some control over the size of the allocated 8503blocks (whose size is the minimum of the default secondary stack size value, 8504and the actual size needed for the current allocation request). 8505 8506For certain targets, notably VxWorks 653, 8507the secondary stack is allocated by carving off a fixed ratio chunk of the 8508primary task stack. The -D option is used to define the 8509size of the environment task's secondary stack. 8510 8511@item ^-e^/ELABORATION_DEPENDENCIES^ 8512@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind}) 8513Output complete list of elaboration-order dependencies. 8514 8515@item ^-E^/STORE_TRACEBACKS^ 8516@cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind}) 8517Store tracebacks in exception occurrences when the target supports it. 8518@ignore 8519@c The following may get moved to an appendix 8520This option is currently supported on the following targets: 8521all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks. 8522@end ignore 8523See also the packages @code{GNAT.Traceback} and 8524@code{GNAT.Traceback.Symbolic} for more information. 8525@ifclear vms 8526Note that on x86 ports, you must not use @option{-fomit-frame-pointer} 8527@command{gcc} option. 8528@end ifclear 8529 8530@item ^-F^/FORCE_ELABS_FLAGS^ 8531@cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind}) 8532Force the checks of elaboration flags. @command{gnatbind} does not normally 8533generate checks of elaboration flags for the main executable, except when 8534a Stand-Alone Library is used. However, there are cases when this cannot be 8535detected by gnatbind. An example is importing an interface of a Stand-Alone 8536Library through a pragma Import and only specifying through a linker switch 8537this Stand-Alone Library. This switch is used to guarantee that elaboration 8538flag checks are generated. 8539 8540@item ^-h^/HELP^ 8541@cindex @option{^-h^/HELP^} (@command{gnatbind}) 8542Output usage (help) information 8543 8544@item ^-H32^/32_MALLOC^ 8545@cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind}) 8546Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types). 8547For further details see @ref{Dynamic Allocation Control}. 8548 8549@item ^-H64^/64_MALLOC^ 8550@cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind}) 8551Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types). 8552@cindex @code{__gnat_malloc} 8553For further details see @ref{Dynamic Allocation Control}. 8554 8555@item ^-I^/SEARCH^ 8556@cindex @option{^-I^/SEARCH^} (@command{gnatbind}) 8557Specify directory to be searched for source and ALI files. 8558 8559@item ^-I-^/NOCURRENT_DIRECTORY^ 8560@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind}) 8561Do not look for sources in the current directory where @code{gnatbind} was 8562invoked, and do not look for ALI files in the directory containing the 8563ALI file named in the @code{gnatbind} command line. 8564 8565@item ^-l^/ORDER_OF_ELABORATION^ 8566@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind}) 8567Output chosen elaboration order. 8568 8569@item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^ 8570@cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind}) 8571Bind the units for library building. In this case the adainit and 8572adafinal procedures (@pxref{Binding with Non-Ada Main Programs}) 8573are renamed to ^@var{xxx}init^@var{XXX}INIT^ and 8574^@var{xxx}final^@var{XXX}FINAL^. 8575Implies ^-n^/NOCOMPILE^. 8576@ifclear vms 8577(@xref{GNAT and Libraries}, for more details.) 8578@end ifclear 8579@ifset vms 8580On OpenVMS, these init and final procedures are exported in uppercase 8581letters. For example if /BUILD_LIBRARY=toto is used, the exported name of 8582the init procedure will be "TOTOINIT" and the exported name of the final 8583procedure will be "TOTOFINAL". 8584@end ifset 8585 8586@item ^-Mxyz^/RENAME_MAIN=xyz^ 8587@cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind}) 8588Rename generated main program from main to xyz. This option is 8589supported on cross environments only. 8590 8591@item ^-m^/ERROR_LIMIT=^@var{n} 8592@cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind}) 8593Limit number of detected errors or warnings to @var{n}, where @var{n} is 8594in the range 1..999999. The default value if no switch is 8595given is 9999. If the number of warnings reaches this limit, then a 8596message is output and further warnings are suppressed, the bind 8597continues in this case. If the number of errors reaches this 8598limit, then a message is output and the bind is abandoned. 8599A value of zero means that no limit is enforced. The equal 8600sign is optional. 8601 8602@ifset unw 8603Furthermore, under Windows, the sources pointed to by the libraries path 8604set in the registry are not searched for. 8605@end ifset 8606 8607@item ^-n^/NOMAIN^ 8608@cindex @option{^-n^/NOMAIN^} (@command{gnatbind}) 8609No main program. 8610 8611@item -nostdinc 8612@cindex @option{-nostdinc} (@command{gnatbind}) 8613Do not look for sources in the system default directory. 8614 8615@item -nostdlib 8616@cindex @option{-nostdlib} (@command{gnatbind}) 8617Do not look for library files in the system default directory. 8618 8619@item --RTS=@var{rts-path} 8620@cindex @option{--RTS} (@code{gnatbind}) 8621Specifies the default location of the runtime library. Same meaning as the 8622equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}). 8623 8624@item ^-o ^/OUTPUT=^@var{file} 8625@cindex @option{^-o ^/OUTPUT^} (@command{gnatbind}) 8626Name the output file @var{file} (default is @file{b~@var{xxx}.adb}). 8627Note that if this option is used, then linking must be done manually, 8628gnatlink cannot be used. 8629 8630@item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]} 8631@cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind}) 8632Output object list (to standard output or to the named file). 8633 8634@item ^-p^/PESSIMISTIC_ELABORATION^ 8635@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind}) 8636Pessimistic (worst-case) elaboration order 8637 8638@item ^-P^-P^ 8639@cindex @option{^-P^/CODEPEER^} (@command{gnatbind}) 8640Generate binder file suitable for CodePeer. 8641 8642@item ^-R^-R^ 8643@cindex @option{^-R^-R^} (@command{gnatbind}) 8644Output closure source list. 8645 8646@item ^-s^/READ_SOURCES=ALL^ 8647@cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind}) 8648Require all source files to be present. 8649 8650@item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^ 8651@cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind}) 8652Specifies the value to be used when detecting uninitialized scalar 8653objects with pragma Initialize_Scalars. 8654The @var{xxx} ^string specified with the switch^option^ may be either 8655@itemize @bullet 8656@item ``@option{^in^INVALID^}'' requesting an invalid value where possible 8657@item ``@option{^lo^LOW^}'' for the lowest possible value 8658@item ``@option{^hi^HIGH^}'' for the highest possible value 8659@item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the 8660value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits). 8661@end itemize 8662 8663In addition, you can specify @option{-Sev} to indicate that the value is 8664to be set at run time. In this case, the program will look for an environment 8665@cindex GNAT_INIT_SCALARS 8666variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one 8667of @option{in/lo/hi/@var{xx}} with the same meanings as above. 8668If no environment variable is found, or if it does not have a valid value, 8669then the default is @option{in} (invalid values). 8670 8671@ifclear vms 8672@item -static 8673@cindex @option{-static} (@code{gnatbind}) 8674Link against a static GNAT run time. 8675 8676@item -shared 8677@cindex @option{-shared} (@code{gnatbind}) 8678Link against a shared GNAT run time when available. 8679@end ifclear 8680 8681@item ^-t^/NOTIME_STAMP_CHECK^ 8682@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind}) 8683Tolerate time stamp and other consistency errors 8684 8685@item ^-T@var{n}^/TIME_SLICE=@var{n}^ 8686@cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind}) 8687Set the time slice value to @var{n} milliseconds. If the system supports 8688the specification of a specific time slice value, then the indicated value 8689is used. If the system does not support specific time slice values, but 8690does support some general notion of round-robin scheduling, then any 8691nonzero value will activate round-robin scheduling. 8692 8693A value of zero is treated specially. It turns off time 8694slicing, and in addition, indicates to the tasking run time that the 8695semantics should match as closely as possible the Annex D 8696requirements of the Ada RM, and in particular sets the default 8697scheduling policy to @code{FIFO_Within_Priorities}. 8698 8699@item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^ 8700@cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind}) 8701Enable dynamic stack usage, with @var{n} results stored and displayed 8702at program termination. A result is generated when a task 8703terminates. Results that can't be stored are displayed on the fly, at 8704task termination. This option is currently not supported on Itanium 8705platforms. (See @ref{Dynamic Stack Usage Analysis} for details.) 8706 8707@item ^-v^/REPORT_ERRORS=VERBOSE^ 8708@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind}) 8709Verbose mode. Write error messages, header, summary output to 8710@file{stdout}. 8711 8712@ifclear vms 8713@item -w@var{x} 8714@cindex @option{-w} (@code{gnatbind}) 8715Warning mode (@var{x}=s/e for suppress/treat as error) 8716@end ifclear 8717 8718@ifset vms 8719@item /WARNINGS=NORMAL 8720@cindex @option{/WARNINGS} (@code{gnatbind}) 8721Normal warnings mode. Warnings are issued but ignored 8722 8723@item /WARNINGS=SUPPRESS 8724@cindex @option{/WARNINGS} (@code{gnatbind}) 8725All warning messages are suppressed 8726 8727@item /WARNINGS=ERROR 8728@cindex @option{/WARNINGS} (@code{gnatbind}) 8729Warning messages are treated as fatal errors 8730@end ifset 8731 8732@item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e} 8733@cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind}) 8734Override default wide character encoding for standard Text_IO files. 8735 8736@item ^-x^/READ_SOURCES=NONE^ 8737@cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind}) 8738Exclude source files (check object consistency only). 8739 8740@ifset vms 8741@item /READ_SOURCES=AVAILABLE 8742@cindex @option{/READ_SOURCES} (@code{gnatbind}) 8743Default mode, in which sources are checked for consistency only if 8744they are available. 8745@end ifset 8746 8747@item ^-y^/ENABLE_LEAP_SECONDS^ 8748@cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind}) 8749Enable leap seconds support in @code{Ada.Calendar} and its children. 8750 8751@item ^-z^/ZERO_MAIN^ 8752@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind}) 8753No main subprogram. 8754@end table 8755 8756@ifclear vms 8757@noindent 8758You may obtain this listing of switches by running @code{gnatbind} with 8759no arguments. 8760@end ifclear 8761 8762@node Consistency-Checking Modes 8763@subsection Consistency-Checking Modes 8764 8765@noindent 8766As described earlier, by default @code{gnatbind} checks 8767that object files are consistent with one another and are consistent 8768with any source files it can locate. The following switches control binder 8769access to sources. 8770 8771@table @option 8772@c !sort! 8773@item ^-s^/READ_SOURCES=ALL^ 8774@cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind}) 8775Require source files to be present. In this mode, the binder must be 8776able to locate all source files that are referenced, in order to check 8777their consistency. In normal mode, if a source file cannot be located it 8778is simply ignored. If you specify this switch, a missing source 8779file is an error. 8780 8781@item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e} 8782@cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind}) 8783Override default wide character encoding for standard Text_IO files. 8784Normally the default wide character encoding method used for standard 8785[Wide_[Wide_]]Text_IO files is taken from the encoding specified for 8786the main source input (see description of switch 8787@option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The 8788use of this switch for the binder (which has the same set of 8789possible arguments) overrides this default as specified. 8790 8791@item ^-x^/READ_SOURCES=NONE^ 8792@cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind}) 8793Exclude source files. In this mode, the binder only checks that ALI 8794files are consistent with one another. Source files are not accessed. 8795The binder runs faster in this mode, and there is still a guarantee that 8796the resulting program is self-consistent. 8797If a source file has been edited since it was last compiled, and you 8798specify this switch, the binder will not detect that the object 8799file is out of date with respect to the source file. Note that this is the 8800mode that is automatically used by @command{gnatmake} because in this 8801case the checking against sources has already been performed by 8802@command{gnatmake} in the course of compilation (i.e.@: before binding). 8803 8804@ifset vms 8805@item /READ_SOURCES=AVAILABLE 8806@cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind}) 8807This is the default mode in which source files are checked if they are 8808available, and ignored if they are not available. 8809@end ifset 8810@end table 8811 8812@node Binder Error Message Control 8813@subsection Binder Error Message Control 8814 8815@noindent 8816The following switches provide control over the generation of error 8817messages from the binder: 8818 8819@table @option 8820@c !sort! 8821@item ^-v^/REPORT_ERRORS=VERBOSE^ 8822@cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind}) 8823Verbose mode. In the normal mode, brief error messages are generated to 8824@file{stderr}. If this switch is present, a header is written 8825to @file{stdout} and any error messages are directed to @file{stdout}. 8826All that is written to @file{stderr} is a brief summary message. 8827 8828@item ^-b^/REPORT_ERRORS=BRIEF^ 8829@cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind}) 8830Generate brief error messages to @file{stderr} even if verbose mode is 8831specified. This is relevant only when used with the 8832@option{^-v^/REPORT_ERRORS=VERBOSE^} switch. 8833 8834@ifclear vms 8835@item -m@var{n} 8836@cindex @option{-m} (@code{gnatbind}) 8837Limits the number of error messages to @var{n}, a decimal integer in the 8838range 1-999. The binder terminates immediately if this limit is reached. 8839 8840@item -M@var{xxx} 8841@cindex @option{-M} (@code{gnatbind}) 8842Renames the generated main program from @code{main} to @code{xxx}. 8843This is useful in the case of some cross-building environments, where 8844the actual main program is separate from the one generated 8845by @code{gnatbind}. 8846@end ifclear 8847 8848@item ^-ws^/WARNINGS=SUPPRESS^ 8849@cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind}) 8850@cindex Warnings 8851Suppress all warning messages. 8852 8853@item ^-we^/WARNINGS=ERROR^ 8854@cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind}) 8855Treat any warning messages as fatal errors. 8856 8857@ifset vms 8858@item /WARNINGS=NORMAL 8859Standard mode with warnings generated, but warnings do not get treated 8860as errors. 8861@end ifset 8862 8863@item ^-t^/NOTIME_STAMP_CHECK^ 8864@cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind}) 8865@cindex Time stamp checks, in binder 8866@cindex Binder consistency checks 8867@cindex Consistency checks, in binder 8868The binder performs a number of consistency checks including: 8869 8870@itemize @bullet 8871@item 8872Check that time stamps of a given source unit are consistent 8873@item 8874Check that checksums of a given source unit are consistent 8875@item 8876Check that consistent versions of @code{GNAT} were used for compilation 8877@item 8878Check consistency of configuration pragmas as required 8879@end itemize 8880 8881@noindent 8882Normally failure of such checks, in accordance with the consistency 8883requirements of the Ada Reference Manual, causes error messages to be 8884generated which abort the binder and prevent the output of a binder 8885file and subsequent link to obtain an executable. 8886 8887The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages 8888into warnings, so that 8889binding and linking can continue to completion even in the presence of such 8890errors. The result may be a failed link (due to missing symbols), or a 8891non-functional executable which has undefined semantics. 8892@emph{This means that 8893@option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations, 8894with extreme care.} 8895@end table 8896 8897@node Elaboration Control 8898@subsection Elaboration Control 8899 8900@noindent 8901The following switches provide additional control over the elaboration 8902order. For full details see @ref{Elaboration Order Handling in GNAT}. 8903 8904@table @option 8905@item ^-p^/PESSIMISTIC_ELABORATION^ 8906@cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind}) 8907Normally the binder attempts to choose an elaboration order that is 8908likely to minimize the likelihood of an elaboration order error resulting 8909in raising a @code{Program_Error} exception. This switch reverses the 8910action of the binder, and requests that it deliberately choose an order 8911that is likely to maximize the likelihood of an elaboration error. 8912This is useful in ensuring portability and avoiding dependence on 8913accidental fortuitous elaboration ordering. 8914 8915Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^} 8916switch if dynamic 8917elaboration checking is used (@option{-gnatE} switch used for compilation). 8918This is because in the default static elaboration mode, all necessary 8919@code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted. 8920These implicit pragmas are still respected by the binder in 8921@option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a 8922safe elaboration order is assured. 8923 8924Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for 8925production use; it is more for debugging/experimental use. 8926@end table 8927 8928@node Output Control 8929@subsection Output Control 8930 8931@noindent 8932The following switches allow additional control over the output 8933generated by the binder. 8934 8935@table @option 8936@c !sort! 8937 8938@item ^-c^/NOOUTPUT^ 8939@cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind}) 8940Check only. Do not generate the binder output file. In this mode the 8941binder performs all error checks but does not generate an output file. 8942 8943@item ^-e^/ELABORATION_DEPENDENCIES^ 8944@cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind}) 8945Output complete list of elaboration-order dependencies, showing the 8946reason for each dependency. This output can be rather extensive but may 8947be useful in diagnosing problems with elaboration order. The output is 8948written to @file{stdout}. 8949 8950@item ^-h^/HELP^ 8951@cindex @option{^-h^/HELP^} (@code{gnatbind}) 8952Output usage information. The output is written to @file{stdout}. 8953 8954@item ^-K^/LINKER_OPTION_LIST^ 8955@cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind}) 8956Output linker options to @file{stdout}. Includes library search paths, 8957contents of pragmas Ident and Linker_Options, and libraries added 8958by @code{gnatbind}. 8959 8960@item ^-l^/ORDER_OF_ELABORATION^ 8961@cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind}) 8962Output chosen elaboration order. The output is written to @file{stdout}. 8963 8964@item ^-O^/OBJECT_LIST^ 8965@cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind}) 8966Output full names of all the object files that must be linked to provide 8967the Ada component of the program. The output is written to @file{stdout}. 8968This list includes the files explicitly supplied and referenced by the user 8969as well as implicitly referenced run-time unit files. The latter are 8970omitted if the corresponding units reside in shared libraries. The 8971directory names for the run-time units depend on the system configuration. 8972 8973@item ^-o ^/OUTPUT=^@var{file} 8974@cindex @option{^-o^/OUTPUT^} (@code{gnatbind}) 8975Set name of output file to @var{file} instead of the normal 8976@file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada 8977binder generated body filename. 8978Note that if this option is used, then linking must be done manually. 8979It is not possible to use gnatlink in this case, since it cannot locate 8980the binder file. 8981 8982@item ^-r^/RESTRICTION_LIST^ 8983@cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind}) 8984Generate list of @code{pragma Restrictions} that could be applied to 8985the current unit. This is useful for code audit purposes, and also may 8986be used to improve code generation in some cases. 8987 8988@end table 8989 8990@node Dynamic Allocation Control 8991@subsection Dynamic Allocation Control 8992 8993@noindent 8994The heap control switches -- @option{-H32} and @option{-H64} -- 8995determine whether dynamic allocation uses 32-bit or 64-bit memory. 8996They only affect compiler-generated allocations via @code{__gnat_malloc}; 8997explicit calls to @code{malloc} and related functions from the C 8998run-time library are unaffected. 8999 9000@table @option 9001@item -H32 9002Allocate memory on 32-bit heap 9003 9004@item -H64 9005Allocate memory on 64-bit heap. This is the default 9006unless explicitly overridden by a @code{'Size} clause on the access type. 9007@end table 9008 9009@ifset vms 9010@noindent 9011See also @ref{Access types and 32/64-bit allocation}. 9012@end ifset 9013@ifclear vms 9014@noindent 9015These switches are only effective on VMS platforms. 9016@end ifclear 9017 9018 9019@node Binding with Non-Ada Main Programs 9020@subsection Binding with Non-Ada Main Programs 9021 9022@noindent 9023In our description so far we have assumed that the main 9024program is in Ada, and that the task of the binder is to generate a 9025corresponding function @code{main} that invokes this Ada main 9026program. GNAT also supports the building of executable programs where 9027the main program is not in Ada, but some of the called routines are 9028written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}). 9029The following switch is used in this situation: 9030 9031@table @option 9032@item ^-n^/NOMAIN^ 9033@cindex @option{^-n^/NOMAIN^} (@code{gnatbind}) 9034No main program. The main program is not in Ada. 9035@end table 9036 9037@noindent 9038In this case, most of the functions of the binder are still required, 9039but instead of generating a main program, the binder generates a file 9040containing the following callable routines: 9041 9042@table @code 9043@item adainit 9044@findex adainit 9045You must call this routine to initialize the Ada part of the program by 9046calling the necessary elaboration routines. A call to @code{adainit} is 9047required before the first call to an Ada subprogram. 9048 9049Note that it is assumed that the basic execution environment must be setup 9050to be appropriate for Ada execution at the point where the first Ada 9051subprogram is called. In particular, if the Ada code will do any 9052floating-point operations, then the FPU must be setup in an appropriate 9053manner. For the case of the x86, for example, full precision mode is 9054required. The procedure GNAT.Float_Control.Reset may be used to ensure 9055that the FPU is in the right state. 9056 9057@item adafinal 9058@findex adafinal 9059You must call this routine to perform any library-level finalization 9060required by the Ada subprograms. A call to @code{adafinal} is required 9061after the last call to an Ada subprogram, and before the program 9062terminates. 9063@end table 9064 9065@noindent 9066If the @option{^-n^/NOMAIN^} switch 9067@cindex @option{^-n^/NOMAIN^} (@command{gnatbind}) 9068@cindex Binder, multiple input files 9069is given, more than one ALI file may appear on 9070the command line for @code{gnatbind}. The normal @dfn{closure} 9071calculation is performed for each of the specified units. Calculating 9072the closure means finding out the set of units involved by tracing 9073@code{with} references. The reason it is necessary to be able to 9074specify more than one ALI file is that a given program may invoke two or 9075more quite separate groups of Ada units. 9076 9077The binder takes the name of its output file from the last specified ALI 9078file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}. 9079@cindex @option{^-o^/OUTPUT^} (@command{gnatbind}) 9080The output is an Ada unit in source form that can be compiled with GNAT. 9081This compilation occurs automatically as part of the @command{gnatlink} 9082processing. 9083 9084Currently the GNAT run time requires a FPU using 80 bits mode 9085precision. Under targets where this is not the default it is required to 9086call GNAT.Float_Control.Reset before using floating point numbers (this 9087include float computation, float input and output) in the Ada code. A 9088side effect is that this could be the wrong mode for the foreign code 9089where floating point computation could be broken after this call. 9090 9091@node Binding Programs with No Main Subprogram 9092@subsection Binding Programs with No Main Subprogram 9093 9094@noindent 9095It is possible to have an Ada program which does not have a main 9096subprogram. This program will call the elaboration routines of all the 9097packages, then the finalization routines. 9098 9099The following switch is used to bind programs organized in this manner: 9100 9101@table @option 9102@item ^-z^/ZERO_MAIN^ 9103@cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind}) 9104Normally the binder checks that the unit name given on the command line 9105corresponds to a suitable main subprogram. When this switch is used, 9106a list of ALI files can be given, and the execution of the program 9107consists of elaboration of these units in an appropriate order. Note 9108that the default wide character encoding method for standard Text_IO 9109files is always set to Brackets if this switch is set (you can use 9110the binder switch 9111@option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default). 9112@end table 9113 9114@node Command-Line Access 9115@section Command-Line Access 9116 9117@noindent 9118The package @code{Ada.Command_Line} provides access to the command-line 9119arguments and program name. In order for this interface to operate 9120correctly, the two variables 9121 9122@smallexample 9123@group 9124int gnat_argc; 9125char **gnat_argv; 9126@end group 9127@end smallexample 9128 9129@noindent 9130@findex gnat_argv 9131@findex gnat_argc 9132are declared in one of the GNAT library routines. These variables must 9133be set from the actual @code{argc} and @code{argv} values passed to the 9134main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind} 9135generates the C main program to automatically set these variables. 9136If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to 9137set these variables. If they are not set, the procedures in 9138@code{Ada.Command_Line} will not be available, and any attempt to use 9139them will raise @code{Constraint_Error}. If command line access is 9140required, your main program must set @code{gnat_argc} and 9141@code{gnat_argv} from the @code{argc} and @code{argv} values passed to 9142it. 9143 9144@node Search Paths for gnatbind 9145@section Search Paths for @code{gnatbind} 9146 9147@noindent 9148The binder takes the name of an ALI file as its argument and needs to 9149locate source files as well as other ALI files to verify object consistency. 9150 9151For source files, it follows exactly the same search rules as @command{gcc} 9152(@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the 9153directories searched are: 9154 9155@enumerate 9156@item 9157The directory containing the ALI file named in the command line, unless 9158the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified. 9159 9160@item 9161All directories specified by @option{^-I^/SEARCH^} 9162switches on the @code{gnatbind} 9163command line, in the order given. 9164 9165@item 9166@findex ADA_PRJ_OBJECTS_FILE 9167Each of the directories listed in the text file whose name is given 9168by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^. 9169 9170@noindent 9171@env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^ 9172driver when project files are used. It should not normally be set 9173by other means. 9174 9175@item 9176@findex ADA_OBJECTS_PATH 9177Each of the directories listed in the value of the 9178@env{ADA_OBJECTS_PATH} ^environment variable^logical name^. 9179@ifset unw 9180Construct this value 9181exactly as the @env{PATH} environment variable: a list of directory 9182names separated by colons (semicolons when working with the NT version 9183of GNAT). 9184@end ifset 9185@ifset vms 9186Normally, define this value as a logical name containing a comma separated 9187list of directory names. 9188 9189This variable can also be defined by means of an environment string 9190(an argument to the HP C exec* set of functions). 9191 9192Logical Name: 9193@smallexample 9194DEFINE ANOTHER_PATH FOO:[BAG] 9195DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR] 9196@end smallexample 9197 9198By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB] 9199first, followed by the standard Ada 9200libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB]. 9201If this is not redefined, the user will obtain the HP Ada 83 IO packages 9202(Text_IO, Sequential_IO, etc) 9203instead of the standard Ada packages. Thus, in order to get the standard Ada 9204packages by default, ADA_OBJECTS_PATH must be redefined. 9205@end ifset 9206 9207@item 9208The content of the @file{ada_object_path} file which is part of the GNAT 9209installation tree and is used to store standard libraries such as the 9210GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is 9211specified. 9212@ifclear vms 9213@ref{Installing a library} 9214@end ifclear 9215@end enumerate 9216 9217@noindent 9218In the binder the switch @option{^-I^/SEARCH^} 9219@cindex @option{^-I^/SEARCH^} (@command{gnatbind}) 9220is used to specify both source and 9221library file paths. Use @option{^-aI^/SOURCE_SEARCH^} 9222@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind}) 9223instead if you want to specify 9224source paths only, and @option{^-aO^/LIBRARY_SEARCH^} 9225@cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind}) 9226if you want to specify library paths 9227only. This means that for the binder 9228@option{^-I^/SEARCH=^}@var{dir} is equivalent to 9229@option{^-aI^/SOURCE_SEARCH=^}@var{dir} 9230@option{^-aO^/OBJECT_SEARCH=^}@var{dir}. 9231The binder generates the bind file (a C language source file) in the 9232current working directory. 9233 9234@findex Ada 9235@findex System 9236@findex Interfaces 9237@findex GNAT 9238The packages @code{Ada}, @code{System}, and @code{Interfaces} and their 9239children make up the GNAT Run-Time Library, together with the package 9240GNAT and its children, which contain a set of useful additional 9241library functions provided by GNAT. The sources for these units are 9242needed by the compiler and are kept together in one directory. The ALI 9243files and object files generated by compiling the RTL are needed by the 9244binder and the linker and are kept together in one directory, typically 9245different from the directory containing the sources. In a normal 9246installation, you need not specify these directory names when compiling 9247or binding. Either the environment variables or the built-in defaults 9248cause these files to be found. 9249 9250Besides simplifying access to the RTL, a major use of search paths is 9251in compiling sources from multiple directories. This can make 9252development environments much more flexible. 9253 9254@node Examples of gnatbind Usage 9255@section Examples of @code{gnatbind} Usage 9256 9257@noindent 9258This section contains a number of examples of using the GNAT binding 9259utility @code{gnatbind}. 9260 9261@table @code 9262@item gnatbind hello 9263The main program @code{Hello} (source program in @file{hello.adb}) is 9264bound using the standard switch settings. The generated main program is 9265@file{b~hello.adb}. This is the normal, default use of the binder. 9266 9267@ifclear vms 9268@item gnatbind hello -o mainprog.adb 9269@end ifclear 9270@ifset vms 9271@item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB 9272@end ifset 9273The main program @code{Hello} (source program in @file{hello.adb}) is 9274bound using the standard switch settings. The generated main program is 9275@file{mainprog.adb} with the associated spec in 9276@file{mainprog.ads}. Note that you must specify the body here not the 9277spec. Note that if this option is used, then linking must be done manually, 9278since gnatlink will not be able to find the generated file. 9279@end table 9280 9281@c ------------------------------------ 9282@node Linking Using gnatlink 9283@chapter Linking Using @command{gnatlink} 9284@c ------------------------------------ 9285@findex gnatlink 9286 9287@noindent 9288This chapter discusses @command{gnatlink}, a tool that links 9289an Ada program and builds an executable file. This utility 9290invokes the system linker ^(via the @command{gcc} command)^^ 9291with a correct list of object files and library references. 9292@command{gnatlink} automatically determines the list of files and 9293references for the Ada part of a program. It uses the binder file 9294generated by the @command{gnatbind} to determine this list. 9295 9296Note: to invoke @code{gnatlink} with a project file, use the @code{gnat} 9297driver (see @ref{The GNAT Driver and Project Files}). 9298 9299@menu 9300* Running gnatlink:: 9301* Switches for gnatlink:: 9302@end menu 9303 9304@node Running gnatlink 9305@section Running @command{gnatlink} 9306 9307@noindent 9308The form of the @command{gnatlink} command is 9309 9310@smallexample 9311@c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]} 9312@c @ovar{non-Ada objects} @ovar{linker options} 9313@c Expanding @ovar macro inline (explanation in macro def comments) 9314$ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} 9315 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]} 9316 9317@end smallexample 9318 9319@noindent 9320The arguments of @command{gnatlink} (switches, main @file{ALI} file, 9321non-Ada objects 9322or linker options) may be in any order, provided that no non-Ada object may 9323be mistaken for a main @file{ALI} file. 9324Any file name @file{F} without the @file{.ali} 9325extension will be taken as the main @file{ALI} file if a file exists 9326whose name is the concatenation of @file{F} and @file{.ali}. 9327 9328@noindent 9329@file{@var{mainprog}.ali} references the ALI file of the main program. 9330The @file{.ali} extension of this file can be omitted. From this 9331reference, @command{gnatlink} locates the corresponding binder file 9332@file{b~@var{mainprog}.adb} and, using the information in this file along 9333with the list of non-Ada objects and linker options, constructs a 9334linker command file to create the executable. 9335 9336The arguments other than the @command{gnatlink} switches and the main 9337@file{ALI} file are passed to the linker uninterpreted. 9338They typically include the names of 9339object files for units written in other languages than Ada and any library 9340references required to resolve references in any of these foreign language 9341units, or in @code{Import} pragmas in any Ada units. 9342 9343@var{linker options} is an optional list of linker specific 9344switches. 9345The default linker called by gnatlink is @command{gcc} which in 9346turn calls the appropriate system linker. 9347 9348One useful option for the linker is @option{-s}: it reduces the size of the 9349executable by removing all symbol table and relocation information from the 9350executable. 9351 9352Standard options for the linker such as @option{-lmy_lib} or 9353@option{-Ldir} can be added as is. 9354For options that are not recognized by 9355@command{gcc} as linker options, use the @command{gcc} switches 9356@option{-Xlinker} or @option{-Wl,}. 9357 9358Refer to the GCC documentation for 9359details. 9360 9361Here is an example showing how to generate a linker map: 9362 9363@smallexample 9364$ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^ 9365@end smallexample 9366 9367Using @var{linker options} it is possible to set the program stack and 9368heap size. 9369@ifset unw 9370See @ref{Setting Stack Size from gnatlink} and 9371@ref{Setting Heap Size from gnatlink}. 9372@end ifset 9373 9374@command{gnatlink} determines the list of objects required by the Ada 9375program and prepends them to the list of objects passed to the linker. 9376@command{gnatlink} also gathers any arguments set by the use of 9377@code{pragma Linker_Options} and adds them to the list of arguments 9378presented to the linker. 9379 9380@ifset vms 9381@command{gnatlink} accepts the following types of extra files on the command 9382line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images 9383(@file{.EXE}), and options files (@file{.OPT}). These are recognized and 9384handled according to their extension. 9385@end ifset 9386 9387@node Switches for gnatlink 9388@section Switches for @command{gnatlink} 9389 9390@noindent 9391The following switches are available with the @command{gnatlink} utility: 9392 9393@table @option 9394@c !sort! 9395 9396@item --version 9397@cindex @option{--version} @command{gnatlink} 9398Display Copyright and version, then exit disregarding all other options. 9399 9400@item --help 9401@cindex @option{--help} @command{gnatlink} 9402If @option{--version} was not used, display usage, then exit disregarding 9403all other options. 9404 9405@item ^-f^/FORCE_OBJECT_FILE_LIST^ 9406@cindex Command line length 9407@cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink}) 9408On some targets, the command line length is limited, and @command{gnatlink} 9409will generate a separate file for the linker if the list of object files 9410is too long. 9411The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file 9412to be generated even if 9413the limit is not exceeded. This is useful in some cases to deal with 9414special situations where the command line length is exceeded. 9415 9416@item ^-g^/DEBUG^ 9417@cindex Debugging information, including 9418@cindex @option{^-g^/DEBUG^} (@command{gnatlink}) 9419The option to include debugging information causes the Ada bind file (in 9420other words, @file{b~@var{mainprog}.adb}) to be compiled with 9421@option{^-g^/DEBUG^}. 9422In addition, the binder does not delete the @file{b~@var{mainprog}.adb}, 9423@file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files. 9424Without @option{^-g^/DEBUG^}, the binder removes these files by 9425default. The same procedure apply if a C bind file was generated using 9426@option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames 9427are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}. 9428 9429@item ^-n^/NOCOMPILE^ 9430@cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink}) 9431Do not compile the file generated by the binder. This may be used when 9432a link is rerun with different options, but there is no need to recompile 9433the binder file. 9434 9435@item ^-v^/VERBOSE^ 9436@cindex @option{^-v^/VERBOSE^} (@command{gnatlink}) 9437Causes additional information to be output, including a full list of the 9438included object files. This switch option is most useful when you want 9439to see what set of object files are being used in the link step. 9440 9441@item ^-v -v^/VERBOSE/VERBOSE^ 9442@cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink}) 9443Very verbose mode. Requests that the compiler operate in verbose mode when 9444it compiles the binder file, and that the system linker run in verbose mode. 9445 9446@item ^-o ^/EXECUTABLE=^@var{exec-name} 9447@cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink}) 9448@var{exec-name} specifies an alternate name for the generated 9449executable program. If this switch is omitted, the executable has the same 9450name as the main unit. For example, @code{gnatlink try.ali} creates 9451an executable called @file{^try^TRY.EXE^}. 9452 9453@ifclear vms 9454@item -b @var{target} 9455@cindex @option{-b} (@command{gnatlink}) 9456Compile your program to run on @var{target}, which is the name of a 9457system configuration. You must have a GNAT cross-compiler built if 9458@var{target} is not the same as your host system. 9459 9460@item -B@var{dir} 9461@cindex @option{-B} (@command{gnatlink}) 9462Load compiler executables (for example, @code{gnat1}, the Ada compiler) 9463from @var{dir} instead of the default location. Only use this switch 9464when multiple versions of the GNAT compiler are available. 9465@xref{Directory Options,,, gcc, The GNU Compiler Collection}, 9466for further details. You would normally use the @option{-b} or 9467@option{-V} switch instead. 9468 9469@item -M 9470When linking an executable, create a map file. The name of the map file 9471has the same name as the executable with extension ".map". 9472 9473@item -M=mapfile 9474When linking an executable, create a map file. The name of the map file is 9475"mapfile". 9476 9477@item --GCC=@var{compiler_name} 9478@cindex @option{--GCC=compiler_name} (@command{gnatlink}) 9479Program used for compiling the binder file. The default is 9480@command{gcc}. You need to use quotes around @var{compiler_name} if 9481@code{compiler_name} contains spaces or other separator characters. 9482As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to 9483use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always 9484inserted after your command name. Thus in the above example the compiler 9485command that will be used by @command{gnatlink} will be @code{foo -c -x -y}. 9486A limitation of this syntax is that the name and path name of the executable 9487itself must not include any embedded spaces. If the compiler executable is 9488different from the default one (gcc or <prefix>-gcc), then the back-end 9489switches in the ALI file are not used to compile the binder generated source. 9490For example, this is the case with @option{--GCC="foo -x -y"}. But the back end 9491switches will be used for @option{--GCC="gcc -gnatv"}. If several 9492@option{--GCC=compiler_name} are used, only the last @var{compiler_name} 9493is taken into account. However, all the additional switches are also taken 9494into account. Thus, 9495@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to 9496@option{--GCC="bar -x -y -z -t"}. 9497 9498@item --LINK=@var{name} 9499@cindex @option{--LINK=} (@command{gnatlink}) 9500@var{name} is the name of the linker to be invoked. This is especially 9501useful in mixed language programs since languages such as C++ require 9502their own linker to be used. When this switch is omitted, the default 9503name for the linker is @command{gcc}. When this switch is used, the 9504specified linker is called instead of @command{gcc} with exactly the same 9505parameters that would have been passed to @command{gcc} so if the desired 9506linker requires different parameters it is necessary to use a wrapper 9507script that massages the parameters before invoking the real linker. It 9508may be useful to control the exact invocation by using the verbose 9509switch. 9510 9511@end ifclear 9512 9513@ifset vms 9514@item /DEBUG=TRACEBACK 9515@cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink}) 9516This qualifier causes sufficient information to be included in the 9517executable file to allow a traceback, but does not include the full 9518symbol information needed by the debugger. 9519 9520@item /IDENTIFICATION="<string>" 9521@code{"<string>"} specifies the string to be stored in the image file 9522identification field in the image header. 9523It overrides any pragma @code{Ident} specified string. 9524 9525@item /NOINHIBIT-EXEC 9526Generate the executable file even if there are linker warnings. 9527 9528@item /NOSTART_FILES 9529Don't link in the object file containing the ``main'' transfer address. 9530Used when linking with a foreign language main program compiled with an 9531HP compiler. 9532 9533@item /STATIC 9534Prefer linking with object libraries over sharable images, even without 9535/DEBUG. 9536@end ifset 9537 9538@end table 9539 9540@node The GNAT Make Program gnatmake 9541@chapter The GNAT Make Program @command{gnatmake} 9542@findex gnatmake 9543 9544@menu 9545* Running gnatmake:: 9546* Switches for gnatmake:: 9547* Mode Switches for gnatmake:: 9548* Notes on the Command Line:: 9549* How gnatmake Works:: 9550* Examples of gnatmake Usage:: 9551@end menu 9552@noindent 9553A typical development cycle when working on an Ada program consists of 9554the following steps: 9555 9556@enumerate 9557@item 9558Edit some sources to fix bugs. 9559 9560@item 9561Add enhancements. 9562 9563@item 9564Compile all sources affected. 9565 9566@item 9567Rebind and relink. 9568 9569@item 9570Test. 9571@end enumerate 9572 9573@noindent 9574The third step can be tricky, because not only do the modified files 9575@cindex Dependency rules 9576have to be compiled, but any files depending on these files must also be 9577recompiled. The dependency rules in Ada can be quite complex, especially 9578in the presence of overloading, @code{use} clauses, generics and inlined 9579subprograms. 9580 9581@command{gnatmake} automatically takes care of the third and fourth steps 9582of this process. It determines which sources need to be compiled, 9583compiles them, and binds and links the resulting object files. 9584 9585Unlike some other Ada make programs, the dependencies are always 9586accurately recomputed from the new sources. The source based approach of 9587the GNAT compilation model makes this possible. This means that if 9588changes to the source program cause corresponding changes in 9589dependencies, they will always be tracked exactly correctly by 9590@command{gnatmake}. 9591 9592@node Running gnatmake 9593@section Running @command{gnatmake} 9594 9595@noindent 9596The usual form of the @command{gnatmake} command is 9597 9598@smallexample 9599@c $ gnatmake @ovar{switches} @var{file_name} 9600@c @ovar{file_names} @ovar{mode_switches} 9601@c Expanding @ovar macro inline (explanation in macro def comments) 9602$ gnatmake @r{[}@var{switches}@r{]} @var{file_name} 9603 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]} 9604@end smallexample 9605 9606@noindent 9607The only required argument is one @var{file_name}, which specifies 9608a compilation unit that is a main program. Several @var{file_names} can be 9609specified: this will result in several executables being built. 9610If @code{switches} are present, they can be placed before the first 9611@var{file_name}, between @var{file_names} or after the last @var{file_name}. 9612If @var{mode_switches} are present, they must always be placed after 9613the last @var{file_name} and all @code{switches}. 9614 9615If you are using standard file extensions (@file{.adb} and @file{.ads}), then the 9616extension may be omitted from the @var{file_name} arguments. However, if 9617you are using non-standard extensions, then it is required that the 9618extension be given. A relative or absolute directory path can be 9619specified in a @var{file_name}, in which case, the input source file will 9620be searched for in the specified directory only. Otherwise, the input 9621source file will first be searched in the directory where 9622@command{gnatmake} was invoked and if it is not found, it will be search on 9623the source path of the compiler as described in 9624@ref{Search Paths and the Run-Time Library (RTL)}. 9625 9626All @command{gnatmake} output (except when you specify 9627@option{^-M^/DEPENDENCIES_LIST^}) is to 9628@file{stderr}. The output produced by the 9629@option{^-M^/DEPENDENCIES_LIST^} switch is send to 9630@file{stdout}. 9631 9632@node Switches for gnatmake 9633@section Switches for @command{gnatmake} 9634 9635@noindent 9636You may specify any of the following switches to @command{gnatmake}: 9637 9638@table @option 9639@c !sort! 9640 9641@item --version 9642@cindex @option{--version} @command{gnatmake} 9643Display Copyright and version, then exit disregarding all other options. 9644 9645@item --help 9646@cindex @option{--help} @command{gnatmake} 9647If @option{--version} was not used, display usage, then exit disregarding 9648all other options. 9649 9650@ifclear vms 9651@item --GCC=@var{compiler_name} 9652@cindex @option{--GCC=compiler_name} (@command{gnatmake}) 9653Program used for compiling. The default is `@command{gcc}'. You need to use 9654quotes around @var{compiler_name} if @code{compiler_name} contains 9655spaces or other separator characters. As an example @option{--GCC="foo -x 9656-y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your 9657compiler. A limitation of this syntax is that the name and path name of 9658the executable itself must not include any embedded spaces. Note that 9659switch @option{-c} is always inserted after your command name. Thus in the 9660above example the compiler command that will be used by @command{gnatmake} 9661will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are 9662used, only the last @var{compiler_name} is taken into account. However, 9663all the additional switches are also taken into account. Thus, 9664@option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to 9665@option{--GCC="bar -x -y -z -t"}. 9666 9667@item --GNATBIND=@var{binder_name} 9668@cindex @option{--GNATBIND=binder_name} (@command{gnatmake}) 9669Program used for binding. The default is `@code{gnatbind}'. You need to 9670use quotes around @var{binder_name} if @var{binder_name} contains spaces 9671or other separator characters. As an example @option{--GNATBIND="bar -x 9672-y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your 9673binder. Binder switches that are normally appended by @command{gnatmake} 9674to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}. 9675A limitation of this syntax is that the name and path name of the executable 9676itself must not include any embedded spaces. 9677 9678@item --GNATLINK=@var{linker_name} 9679@cindex @option{--GNATLINK=linker_name} (@command{gnatmake}) 9680Program used for linking. The default is `@command{gnatlink}'. You need to 9681use quotes around @var{linker_name} if @var{linker_name} contains spaces 9682or other separator characters. As an example @option{--GNATLINK="lan -x 9683-y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your 9684linker. Linker switches that are normally appended by @command{gnatmake} to 9685`@command{gnatlink}' are now appended to the end of @code{lan -x -y}. 9686A limitation of this syntax is that the name and path name of the executable 9687itself must not include any embedded spaces. 9688 9689@end ifclear 9690 9691@item ^--subdirs^/SUBDIRS^=subdir 9692Actual object directory of each project file is the subdirectory subdir of the 9693object directory specified or defaulted in the project file. 9694 9695@item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^ 9696Disallow simultaneous compilations in the same object directory when 9697project files are used. 9698 9699@item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^ 9700By default, shared library projects are not allowed to import static library 9701projects. When this switch is used on the command line, this restriction is 9702relaxed. 9703 9704@item ^--source-info=<source info file>^/SRC_INFO=source-info-file^ 9705Specify a source info file. This switch is active only when project files 9706are used. If the source info file is specified as a relative path, then it is 9707relative to the object directory of the main project. If the source info file 9708does not exist, then after the Project Manager has successfully parsed and 9709processed the project files and found the sources, it creates the source info 9710file. If the source info file already exists and can be read successfully, 9711then the Project Manager will get all the needed information about the sources 9712from the source info file and will not look for them. This reduces the time 9713to process the project files, especially when looking for sources that take a 9714long time. If the source info file exists but cannot be parsed successfully, 9715the Project Manager will attempt to recreate it. If the Project Manager fails 9716to create the source info file, a message is issued, but gnatmake does not 9717fail. @command{gnatmake} "trusts" the source info file. This means that 9718if the source files have changed (addition, deletion, moving to a different 9719source directory), then the source info file need to be deleted and recreated. 9720 9721@ifclear vms 9722@item --create-map-file 9723When linking an executable, create a map file. The name of the map file 9724has the same name as the executable with extension ".map". 9725 9726@item --create-map-file=mapfile 9727When linking an executable, create a map file. The name of the map file is 9728"mapfile". 9729 9730@end ifclear 9731 9732@item ^-a^/ALL_FILES^ 9733@cindex @option{^-a^/ALL_FILES^} (@command{gnatmake}) 9734Consider all files in the make process, even the GNAT internal system 9735files (for example, the predefined Ada library files), as well as any 9736locked files. Locked files are files whose ALI file is write-protected. 9737By default, 9738@command{gnatmake} does not check these files, 9739because the assumption is that the GNAT internal files are properly up 9740to date, and also that any write protected ALI files have been properly 9741installed. Note that if there is an installation problem, such that one 9742of these files is not up to date, it will be properly caught by the 9743binder. 9744You may have to specify this switch if you are working on GNAT 9745itself. The switch @option{^-a^/ALL_FILES^} is also useful 9746in conjunction with @option{^-f^/FORCE_COMPILE^} 9747if you need to recompile an entire application, 9748including run-time files, using special configuration pragmas, 9749such as a @code{Normalize_Scalars} pragma. 9750 9751By default 9752@code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT 9753internal files with 9754@ifclear vms 9755@code{gcc -c -gnatpg} rather than @code{gcc -c}. 9756@end ifclear 9757@ifset vms 9758the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch. 9759@end ifset 9760 9761@item ^-b^/ACTIONS=BIND^ 9762@cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake}) 9763Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do 9764compilation and binding, but no link. 9765Can be combined with @option{^-l^/ACTIONS=LINK^} 9766to do binding and linking. When not combined with 9767@option{^-c^/ACTIONS=COMPILE^} 9768all the units in the closure of the main program must have been previously 9769compiled and must be up to date. The root unit specified by @var{file_name} 9770may be given without extension, with the source extension or, if no GNAT 9771Project File is specified, with the ALI file extension. 9772 9773@item ^-c^/ACTIONS=COMPILE^ 9774@cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake}) 9775Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^} 9776is also specified. Do not perform linking, except if both 9777@option{^-b^/ACTIONS=BIND^} and 9778@option{^-l^/ACTIONS=LINK^} are also specified. 9779If the root unit specified by @var{file_name} is not a main unit, this is the 9780default. Otherwise @command{gnatmake} will attempt binding and linking 9781unless all objects are up to date and the executable is more recent than 9782the objects. 9783 9784@item ^-C^/MAPPING^ 9785@cindex @option{^-C^/MAPPING^} (@command{gnatmake}) 9786Use a temporary mapping file. A mapping file is a way to communicate 9787to the compiler two mappings: from unit names to file names (without 9788any directory information) and from file names to path names (with 9789full directory information). A mapping file can make the compiler's 9790file searches faster, especially if there are many source directories, 9791or the sources are read over a slow network connection. If 9792@option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so 9793@option{^-C^/MAPPING^} is unnecessary; in this case the mapping file 9794is initially populated based on the project file. If 9795@option{^-C^/MAPPING^} is used without 9796@option{^-P^/PROJECT_FILE^}, 9797the mapping file is initially empty. Each invocation of the compiler 9798will add any newly accessed sources to the mapping file. 9799 9800@item ^-C=^/USE_MAPPING_FILE=^@var{file} 9801@cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake}) 9802Use a specific mapping file. The file, specified as a path name (absolute or 9803relative) by this switch, should already exist, otherwise the switch is 9804ineffective. The specified mapping file will be communicated to the compiler. 9805This switch is not compatible with a project file 9806(^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes 9807(^-j^/PROCESSES=^nnn, when nnn is greater than 1). 9808 9809@item ^-d^/DISPLAY_PROGRESS^ 9810@cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake}) 9811Display progress for each source, up to date or not, as a single line 9812 9813@smallexample 9814completed x out of y (zz%) 9815@end smallexample 9816 9817If the file needs to be compiled this is displayed after the invocation of 9818the compiler. These lines are displayed even in quiet output mode. 9819 9820@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir} 9821@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake}) 9822Put all object files and ALI file in directory @var{dir}. 9823If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files 9824and ALI files go in the current working directory. 9825 9826This switch cannot be used when using a project file. 9827 9828@item -eInnn 9829@cindex @option{-eI} (@command{gnatmake}) 9830Indicates that the main source is a multi-unit source and the rank of the unit 9831in the source file is nnn. nnn needs to be a positive number and a valid 9832index in the source. This switch cannot be used when @command{gnatmake} is 9833invoked for several mains. 9834 9835@ifclear vms 9836@item -eL 9837@cindex @option{-eL} (@command{gnatmake}) 9838@cindex symbolic links 9839Follow all symbolic links when processing project files. 9840This should be used if your project uses symbolic links for files or 9841directories, but is not needed in other cases. 9842 9843@cindex naming scheme 9844This also assumes that no directory matches the naming scheme for files (for 9845instance that you do not have a directory called "sources.ads" when using the 9846default GNAT naming scheme). 9847 9848When you do not have to use this switch (i.e.@: by default), gnatmake is able to 9849save a lot of system calls (several per source file and object file), which 9850can result in a significant speed up to load and manipulate a project file, 9851especially when using source files from a remote system. 9852 9853@end ifclear 9854 9855@item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^ 9856@cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake}) 9857Output the commands for the compiler, the binder and the linker 9858on ^standard output^SYS$OUTPUT^, 9859instead of ^standard error^SYS$ERROR^. 9860 9861@item ^-f^/FORCE_COMPILE^ 9862@cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake}) 9863Force recompilations. Recompile all sources, even though some object 9864files may be up to date, but don't recompile predefined or GNAT internal 9865files or locked files (files with a write-protected ALI file), 9866unless the @option{^-a^/ALL_FILES^} switch is also specified. 9867 9868@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^ 9869@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake}) 9870When using project files, if some errors or warnings are detected during 9871parsing and verbose mode is not in effect (no use of switch 9872^-v^/VERBOSE^), then error lines start with the full path name of the project 9873file, rather than its simple file name. 9874 9875@item ^-g^/DEBUG^ 9876@cindex @option{^-g^/DEBUG^} (@command{gnatmake}) 9877Enable debugging. This switch is simply passed to the compiler and to the 9878linker. 9879 9880@item ^-i^/IN_PLACE^ 9881@cindex @option{^-i^/IN_PLACE^} (@command{gnatmake}) 9882In normal mode, @command{gnatmake} compiles all object files and ALI files 9883into the current directory. If the @option{^-i^/IN_PLACE^} switch is used, 9884then instead object files and ALI files that already exist are overwritten 9885in place. This means that once a large project is organized into separate 9886directories in the desired manner, then @command{gnatmake} will automatically 9887maintain and update this organization. If no ALI files are found on the 9888Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}), 9889the new object and ALI files are created in the 9890directory containing the source being compiled. If another organization 9891is desired, where objects and sources are kept in different directories, 9892a useful technique is to create dummy ALI files in the desired directories. 9893When detecting such a dummy file, @command{gnatmake} will be forced to 9894recompile the corresponding source file, and it will be put the resulting 9895object and ALI files in the directory where it found the dummy file. 9896 9897@item ^-j^/PROCESSES=^@var{n} 9898@cindex @option{^-j^/PROCESSES^} (@command{gnatmake}) 9899@cindex Parallel make 9900Use @var{n} processes to carry out the (re)compilations. On a 9901multiprocessor machine compilations will occur in parallel. In the 9902event of compilation errors, messages from various compilations might 9903get interspersed (but @command{gnatmake} will give you the full ordered 9904list of failing compiles at the end). If this is problematic, rerun 9905the make process with n set to 1 to get a clean list of messages. 9906 9907@item ^-k^/CONTINUE_ON_ERROR^ 9908@cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake}) 9909Keep going. Continue as much as possible after a compilation error. To 9910ease the programmer's task in case of compilation errors, the list of 9911sources for which the compile fails is given when @command{gnatmake} 9912terminates. 9913 9914If @command{gnatmake} is invoked with several @file{file_names} and with this 9915switch, if there are compilation errors when building an executable, 9916@command{gnatmake} will not attempt to build the following executables. 9917 9918@item ^-l^/ACTIONS=LINK^ 9919@cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake}) 9920Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding 9921and linking. Linking will not be performed if combined with 9922@option{^-c^/ACTIONS=COMPILE^} 9923but not with @option{^-b^/ACTIONS=BIND^}. 9924When not combined with @option{^-b^/ACTIONS=BIND^} 9925all the units in the closure of the main program must have been previously 9926compiled and must be up to date, and the main program needs to have been bound. 9927The root unit specified by @var{file_name} 9928may be given without extension, with the source extension or, if no GNAT 9929Project File is specified, with the ALI file extension. 9930 9931@item ^-m^/MINIMAL_RECOMPILATION^ 9932@cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake}) 9933Specify that the minimum necessary amount of recompilations 9934be performed. In this mode @command{gnatmake} ignores time 9935stamp differences when the only 9936modifications to a source file consist in adding/removing comments, 9937empty lines, spaces or tabs. This means that if you have changed the 9938comments in a source file or have simply reformatted it, using this 9939switch will tell @command{gnatmake} not to recompile files that depend on it 9940(provided other sources on which these files depend have undergone no 9941semantic modifications). Note that the debugging information may be 9942out of date with respect to the sources if the @option{-m} switch causes 9943a compilation to be switched, so the use of this switch represents a 9944trade-off between compilation time and accurate debugging information. 9945 9946@item ^-M^/DEPENDENCIES_LIST^ 9947@cindex Dependencies, producing list 9948@cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake}) 9949Check if all objects are up to date. If they are, output the object 9950dependences to @file{stdout} in a form that can be directly exploited in 9951a @file{Makefile}. By default, each source file is prefixed with its 9952(relative or absolute) directory name. This name is whatever you 9953specified in the various @option{^-aI^/SOURCE_SEARCH^} 9954and @option{^-I^/SEARCH^} switches. If you use 9955@code{gnatmake ^-M^/DEPENDENCIES_LIST^} 9956@option{^-q^/QUIET^} 9957(see below), only the source file names, 9958without relative paths, are output. If you just specify the 9959@option{^-M^/DEPENDENCIES_LIST^} 9960switch, dependencies of the GNAT internal system files are omitted. This 9961is typically what you want. If you also specify 9962the @option{^-a^/ALL_FILES^} switch, 9963dependencies of the GNAT internal files are also listed. Note that 9964dependencies of the objects in external Ada libraries (see switch 9965@option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) 9966are never reported. 9967 9968@item ^-n^/DO_OBJECT_CHECK^ 9969@cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake}) 9970Don't compile, bind, or link. Checks if all objects are up to date. 9971If they are not, the full name of the first file that needs to be 9972recompiled is printed. 9973Repeated use of this option, followed by compiling the indicated source 9974file, will eventually result in recompiling all required units. 9975 9976@item ^-o ^/EXECUTABLE=^@var{exec_name} 9977@cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake}) 9978Output executable name. The name of the final executable program will be 9979@var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default 9980name for the executable will be the name of the input file in appropriate form 9981for an executable file on the host system. 9982 9983This switch cannot be used when invoking @command{gnatmake} with several 9984@file{file_names}. 9985 9986@item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^ 9987@cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake}) 9988When using project files (^-P^/PROJECT_FILE=^@var{project}), create 9989automatically missing object directories, library directories and exec 9990directories. 9991 9992@item ^-P^/PROJECT_FILE=^@var{project} 9993@cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake}) 9994Use project file @var{project}. Only one such switch can be used. 9995@xref{gnatmake and Project Files}. 9996 9997@item ^-q^/QUIET^ 9998@cindex @option{^-q^/QUIET^} (@command{gnatmake}) 9999Quiet. When this flag is not set, the commands carried out by 10000@command{gnatmake} are displayed. 10001 10002@item ^-s^/SWITCH_CHECK/^ 10003@cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake}) 10004Recompile if compiler switches have changed since last compilation. 10005All compiler switches but -I and -o are taken into account in the 10006following way: 10007orders between different ``first letter'' switches are ignored, but 10008orders between same switches are taken into account. For example, 10009@option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O} 10010is equivalent to @option{-O -g}. 10011 10012This switch is recommended when Integrated Preprocessing is used. 10013 10014@item ^-u^/UNIQUE^ 10015@cindex @option{^-u^/UNIQUE^} (@command{gnatmake}) 10016Unique. Recompile at most the main files. It implies -c. Combined with 10017-f, it is equivalent to calling the compiler directly. Note that using 10018^-u^/UNIQUE^ with a project file and no main has a special meaning 10019(@pxref{Project Files and Main Subprograms}). 10020 10021@item ^-U^/ALL_PROJECTS^ 10022@cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake}) 10023When used without a project file or with one or several mains on the command 10024line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main 10025on the command line, all sources of all project files are checked and compiled 10026if not up to date, and libraries are rebuilt, if necessary. 10027 10028@item ^-v^/REASONS^ 10029@cindex @option{^-v^/REASONS^} (@command{gnatmake}) 10030Verbose. Display the reason for all recompilations @command{gnatmake} 10031decides are necessary, with the highest verbosity level. 10032 10033@item ^-vl^/LOW_VERBOSITY^ 10034@cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake}) 10035Verbosity level Low. Display fewer lines than in verbosity Medium. 10036 10037@item ^-vm^/MEDIUM_VERBOSITY^ 10038@cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake}) 10039Verbosity level Medium. Potentially display fewer lines than in verbosity High. 10040 10041@item ^-vh^/HIGH_VERBOSITY^ 10042@cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake}) 10043Verbosity level High. Equivalent to ^-v^/REASONS^. 10044 10045@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x} 10046Indicate the verbosity of the parsing of GNAT project files. 10047@xref{Switches Related to Project Files}. 10048 10049@item ^-x^/NON_PROJECT_UNIT_COMPILATION^ 10050@cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake}) 10051Indicate that sources that are not part of any Project File may be compiled. 10052Normally, when using Project Files, only sources that are part of a Project 10053File may be compile. When this switch is used, a source outside of all Project 10054Files may be compiled. The ALI file and the object file will be put in the 10055object directory of the main Project. The compilation switches used will only 10056be those specified on the command line. Even when 10057@option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the 10058command line need to be sources of a project file. 10059 10060@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value} 10061Indicate that external variable @var{name} has the value @var{value}. 10062The Project Manager will use this value for occurrences of 10063@code{external(name)} when parsing the project file. 10064@xref{Switches Related to Project Files}. 10065 10066@item ^-z^/NOMAIN^ 10067@cindex @option{^-z^/NOMAIN^} (@command{gnatmake}) 10068No main subprogram. Bind and link the program even if the unit name 10069given on the command line is a package name. The resulting executable 10070will execute the elaboration routines of the package and its closure, 10071then the finalization routines. 10072 10073@end table 10074 10075@table @asis 10076@item @command{gcc} @asis{switches} 10077@ifclear vms 10078Any uppercase or multi-character switch that is not a @command{gnatmake} switch 10079is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.) 10080@end ifclear 10081@ifset vms 10082Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE} 10083but is recognizable as a valid qualifier for @code{GNAT COMPILE} is 10084automatically treated as a compiler switch, and passed on to all 10085compilations that are carried out. 10086@end ifset 10087@end table 10088 10089@noindent 10090Source and library search path switches: 10091 10092@table @option 10093@c !sort! 10094@item ^-aI^/SOURCE_SEARCH=^@var{dir} 10095@cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake}) 10096When looking for source files also look in directory @var{dir}. 10097The order in which source files search is undertaken is 10098described in @ref{Search Paths and the Run-Time Library (RTL)}. 10099 10100@item ^-aL^/SKIP_MISSING=^@var{dir} 10101@cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake}) 10102Consider @var{dir} as being an externally provided Ada library. 10103Instructs @command{gnatmake} to skip compilation units whose @file{.ALI} 10104files have been located in directory @var{dir}. This allows you to have 10105missing bodies for the units in @var{dir} and to ignore out of date bodies 10106for the same units. You still need to specify 10107the location of the specs for these units by using the switches 10108@option{^-aI^/SOURCE_SEARCH=^@var{dir}} 10109or @option{^-I^/SEARCH=^@var{dir}}. 10110Note: this switch is provided for compatibility with previous versions 10111of @command{gnatmake}. The easier method of causing standard libraries 10112to be excluded from consideration is to write-protect the corresponding 10113ALI files. 10114 10115@item ^-aO^/OBJECT_SEARCH=^@var{dir} 10116@cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake}) 10117When searching for library and object files, look in directory 10118@var{dir}. The order in which library files are searched is described in 10119@ref{Search Paths for gnatbind}. 10120 10121@item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir} 10122@cindex Search paths, for @command{gnatmake} 10123@cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake}) 10124Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir} 10125^-aI^/SOURCE_SEARCH=^@var{dir}}. 10126 10127@item ^-I^/SEARCH=^@var{dir} 10128@cindex @option{^-I^/SEARCH^} (@command{gnatmake}) 10129Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir} 10130^-aI^/SOURCE_SEARCH=^@var{dir}}. 10131 10132@item ^-I-^/NOCURRENT_DIRECTORY^ 10133@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake}) 10134@cindex Source files, suppressing search 10135Do not look for source files in the directory containing the source 10136file named in the command line. 10137Do not look for ALI or object files in the directory 10138where @command{gnatmake} was invoked. 10139 10140@item ^-L^/LIBRARY_SEARCH=^@var{dir} 10141@cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake}) 10142@cindex Linker libraries 10143Add directory @var{dir} to the list of directories in which the linker 10144will search for libraries. This is equivalent to 10145@option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}. 10146@ifclear vms 10147Furthermore, under Windows, the sources pointed to by the libraries path 10148set in the registry are not searched for. 10149@end ifclear 10150 10151@item -nostdinc 10152@cindex @option{-nostdinc} (@command{gnatmake}) 10153Do not look for source files in the system default directory. 10154 10155@item -nostdlib 10156@cindex @option{-nostdlib} (@command{gnatmake}) 10157Do not look for library files in the system default directory. 10158 10159@item --RTS=@var{rts-path} 10160@cindex @option{--RTS} (@command{gnatmake}) 10161Specifies the default location of the runtime library. GNAT looks for the 10162runtime 10163in the following directories, and stops as soon as a valid runtime is found 10164(@file{adainclude} or @file{ada_source_path}, and @file{adalib} or 10165@file{ada_object_path} present): 10166 10167@itemize @bullet 10168@item <current directory>/$rts_path 10169 10170@item <default-search-dir>/$rts_path 10171 10172@item <default-search-dir>/rts-$rts_path 10173@end itemize 10174 10175@noindent 10176The selected path is handled like a normal RTS path. 10177 10178@end table 10179 10180@node Mode Switches for gnatmake 10181@section Mode Switches for @command{gnatmake} 10182 10183@noindent 10184The mode switches (referred to as @code{mode_switches}) allow the 10185inclusion of switches that are to be passed to the compiler itself, the 10186binder or the linker. The effect of a mode switch is to cause all 10187subsequent switches up to the end of the switch list, or up to the next 10188mode switch, to be interpreted as switches to be passed on to the 10189designated component of GNAT. 10190 10191@table @option 10192@c !sort! 10193@item -cargs @var{switches} 10194@cindex @option{-cargs} (@command{gnatmake}) 10195Compiler switches. Here @var{switches} is a list of switches 10196that are valid switches for @command{gcc}. They will be passed on to 10197all compile steps performed by @command{gnatmake}. 10198 10199@item -bargs @var{switches} 10200@cindex @option{-bargs} (@command{gnatmake}) 10201Binder switches. Here @var{switches} is a list of switches 10202that are valid switches for @code{gnatbind}. They will be passed on to 10203all bind steps performed by @command{gnatmake}. 10204 10205@item -largs @var{switches} 10206@cindex @option{-largs} (@command{gnatmake}) 10207Linker switches. Here @var{switches} is a list of switches 10208that are valid switches for @command{gnatlink}. They will be passed on to 10209all link steps performed by @command{gnatmake}. 10210 10211@item -margs @var{switches} 10212@cindex @option{-margs} (@command{gnatmake}) 10213Make switches. The switches are directly interpreted by @command{gnatmake}, 10214regardless of any previous occurrence of @option{-cargs}, @option{-bargs} 10215or @option{-largs}. 10216@end table 10217 10218@node Notes on the Command Line 10219@section Notes on the Command Line 10220 10221@noindent 10222This section contains some additional useful notes on the operation 10223of the @command{gnatmake} command. 10224 10225@itemize @bullet 10226@item 10227@cindex Recompilation, by @command{gnatmake} 10228If @command{gnatmake} finds no ALI files, it recompiles the main program 10229and all other units required by the main program. 10230This means that @command{gnatmake} 10231can be used for the initial compile, as well as during subsequent steps of 10232the development cycle. 10233 10234@item 10235If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb} 10236is a subunit or body of a generic unit, @command{gnatmake} recompiles 10237@file{@var{file}.adb} (because it finds no ALI) and stops, issuing a 10238warning. 10239 10240@item 10241In @command{gnatmake} the switch @option{^-I^/SEARCH^} 10242is used to specify both source and 10243library file paths. Use @option{^-aI^/SOURCE_SEARCH^} 10244instead if you just want to specify 10245source paths only and @option{^-aO^/OBJECT_SEARCH^} 10246if you want to specify library paths 10247only. 10248 10249@item 10250@command{gnatmake} will ignore any files whose ALI file is write-protected. 10251This may conveniently be used to exclude standard libraries from 10252consideration and in particular it means that the use of the 10253@option{^-f^/FORCE_COMPILE^} switch will not recompile these files 10254unless @option{^-a^/ALL_FILES^} is also specified. 10255 10256@item 10257@command{gnatmake} has been designed to make the use of Ada libraries 10258particularly convenient. Assume you have an Ada library organized 10259as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for 10260of your Ada compilation units, 10261whereas @i{^include-dir^[INCLUDE_DIR]^} contains the 10262specs of these units, but no bodies. Then to compile a unit 10263stored in @code{main.adb}, which uses this Ada library you would just type 10264 10265@smallexample 10266@ifclear vms 10267$ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main 10268@end ifclear 10269@ifset vms 10270$ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]} 10271 /SKIP_MISSING=@i{[OBJ_DIR]} main 10272@end ifset 10273@end smallexample 10274 10275@item 10276Using @command{gnatmake} along with the 10277@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^} 10278switch provides a mechanism for avoiding unnecessary recompilations. Using 10279this switch, 10280you can update the comments/format of your 10281source files without having to recompile everything. Note, however, that 10282adding or deleting lines in a source files may render its debugging 10283info obsolete. If the file in question is a spec, the impact is rather 10284limited, as that debugging info will only be useful during the 10285elaboration phase of your program. For bodies the impact can be more 10286significant. In all events, your debugger will warn you if a source file 10287is more recent than the corresponding object, and alert you to the fact 10288that the debugging information may be out of date. 10289@end itemize 10290 10291@node How gnatmake Works 10292@section How @command{gnatmake} Works 10293 10294@noindent 10295Generally @command{gnatmake} automatically performs all necessary 10296recompilations and you don't need to worry about how it works. However, 10297it may be useful to have some basic understanding of the @command{gnatmake} 10298approach and in particular to understand how it uses the results of 10299previous compilations without incorrectly depending on them. 10300 10301First a definition: an object file is considered @dfn{up to date} if the 10302corresponding ALI file exists and if all the source files listed in the 10303dependency section of this ALI file have time stamps matching those in 10304the ALI file. This means that neither the source file itself nor any 10305files that it depends on have been modified, and hence there is no need 10306to recompile this file. 10307 10308@command{gnatmake} works by first checking if the specified main unit is up 10309to date. If so, no compilations are required for the main unit. If not, 10310@command{gnatmake} compiles the main program to build a new ALI file that 10311reflects the latest sources. Then the ALI file of the main unit is 10312examined to find all the source files on which the main program depends, 10313and @command{gnatmake} recursively applies the above procedure on all these 10314files. 10315 10316This process ensures that @command{gnatmake} only trusts the dependencies 10317in an existing ALI file if they are known to be correct. Otherwise it 10318always recompiles to determine a new, guaranteed accurate set of 10319dependencies. As a result the program is compiled ``upside down'' from what may 10320be more familiar as the required order of compilation in some other Ada 10321systems. In particular, clients are compiled before the units on which 10322they depend. The ability of GNAT to compile in any order is critical in 10323allowing an order of compilation to be chosen that guarantees that 10324@command{gnatmake} will recompute a correct set of new dependencies if 10325necessary. 10326 10327When invoking @command{gnatmake} with several @var{file_names}, if a unit is 10328imported by several of the executables, it will be recompiled at most once. 10329 10330Note: when using non-standard naming conventions 10331(@pxref{Using Other File Names}), changing through a configuration pragmas 10332file the version of a source and invoking @command{gnatmake} to recompile may 10333have no effect, if the previous version of the source is still accessible 10334by @command{gnatmake}. It may be necessary to use the switch 10335^-f^/FORCE_COMPILE^. 10336 10337@node Examples of gnatmake Usage 10338@section Examples of @command{gnatmake} Usage 10339 10340@table @code 10341@item gnatmake hello.adb 10342Compile all files necessary to bind and link the main program 10343@file{hello.adb} (containing unit @code{Hello}) and bind and link the 10344resulting object files to generate an executable file @file{^hello^HELLO.EXE^}. 10345 10346@item gnatmake main1 main2 main3 10347Compile all files necessary to bind and link the main programs 10348@file{main1.adb} (containing unit @code{Main1}), @file{main2.adb} 10349(containing unit @code{Main2}) and @file{main3.adb} 10350(containing unit @code{Main3}) and bind and link the resulting object files 10351to generate three executable files @file{^main1^MAIN1.EXE^}, 10352@file{^main2^MAIN2.EXE^} 10353and @file{^main3^MAIN3.EXE^}. 10354 10355@ifclear vms 10356@item gnatmake -q Main_Unit -cargs -O2 -bargs -l 10357@end ifclear 10358 10359@ifset vms 10360@item gnatmake Main_Unit /QUIET 10361/COMPILER_QUALIFIERS /OPTIMIZE=ALL 10362/BINDER_QUALIFIERS /ORDER_OF_ELABORATION 10363@end ifset 10364Compile all files necessary to bind and link the main program unit 10365@code{Main_Unit} (from file @file{main_unit.adb}). All compilations will 10366be done with optimization level 2 and the order of elaboration will be 10367listed by the binder. @command{gnatmake} will operate in quiet mode, not 10368displaying commands it is executing. 10369@end table 10370 10371@c ************************* 10372@node Improving Performance 10373@chapter Improving Performance 10374@cindex Improving performance 10375 10376@noindent 10377This chapter presents several topics related to program performance. 10378It first describes some of the tradeoffs that need to be considered 10379and some of the techniques for making your program run faster. 10380It then documents the @command{gnatelim} tool and unused subprogram/data 10381elimination feature, which can reduce the size of program executables. 10382 10383@ifnottex 10384@menu 10385* Performance Considerations:: 10386* Text_IO Suggestions:: 10387* Reducing Size of Ada Executables with gnatelim:: 10388* Reducing Size of Executables with unused subprogram/data elimination:: 10389@end menu 10390@end ifnottex 10391 10392@c ***************************** 10393@node Performance Considerations 10394@section Performance Considerations 10395 10396@noindent 10397The GNAT system provides a number of options that allow a trade-off 10398between 10399 10400@itemize @bullet 10401@item 10402performance of the generated code 10403 10404@item 10405speed of compilation 10406 10407@item 10408minimization of dependences and recompilation 10409 10410@item 10411the degree of run-time checking. 10412@end itemize 10413 10414@noindent 10415The defaults (if no options are selected) aim at improving the speed 10416of compilation and minimizing dependences, at the expense of performance 10417of the generated code: 10418 10419@itemize @bullet 10420@item 10421no optimization 10422 10423@item 10424no inlining of subprogram calls 10425 10426@item 10427all run-time checks enabled except overflow and elaboration checks 10428@end itemize 10429 10430@noindent 10431These options are suitable for most program development purposes. This 10432chapter describes how you can modify these choices, and also provides 10433some guidelines on debugging optimized code. 10434 10435@menu 10436* Controlling Run-Time Checks:: 10437* Use of Restrictions:: 10438* Optimization Levels:: 10439* Debugging Optimized Code:: 10440* Inlining of Subprograms:: 10441* Vectorization of loops:: 10442* Other Optimization Switches:: 10443* Optimization and Strict Aliasing:: 10444 10445@ifset vms 10446* Coverage Analysis:: 10447@end ifset 10448@end menu 10449 10450@node Controlling Run-Time Checks 10451@subsection Controlling Run-Time Checks 10452 10453@noindent 10454By default, GNAT generates all run-time checks, except integer overflow 10455checks, stack overflow checks, and checks for access before elaboration on 10456subprogram calls. The latter are not required in default mode, because all 10457necessary checking is done at compile time. 10458@cindex @option{-gnatp} (@command{gcc}) 10459@cindex @option{-gnato} (@command{gcc}) 10460Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to 10461be modified. @xref{Run-Time Checks}. 10462 10463Our experience is that the default is suitable for most development 10464purposes. 10465 10466We treat integer overflow specially because these 10467are quite expensive and in our experience are not as important as other 10468run-time checks in the development process. Note that division by zero 10469is not considered an overflow check, and divide by zero checks are 10470generated where required by default. 10471 10472Elaboration checks are off by default, and also not needed by default, since 10473GNAT uses a static elaboration analysis approach that avoids the need for 10474run-time checking. This manual contains a full chapter discussing the issue 10475of elaboration checks, and if the default is not satisfactory for your use, 10476you should read this chapter. 10477 10478For validity checks, the minimal checks required by the Ada Reference 10479Manual (for case statements and assignments to array elements) are on 10480by default. These can be suppressed by use of the @option{-gnatVn} switch. 10481Note that in Ada 83, there were no validity checks, so if the Ada 83 mode 10482is acceptable (or when comparing GNAT performance with an Ada 83 compiler), 10483it may be reasonable to routinely use @option{-gnatVn}. Validity checks 10484are also suppressed entirely if @option{-gnatp} is used. 10485 10486@cindex Overflow checks 10487@cindex Checks, overflow 10488@findex Suppress 10489@findex Unsuppress 10490@cindex pragma Suppress 10491@cindex pragma Unsuppress 10492Note that the setting of the switches controls the default setting of 10493the checks. They may be modified using either @code{pragma Suppress} (to 10494remove checks) or @code{pragma Unsuppress} (to add back suppressed 10495checks) in the program source. 10496 10497@node Use of Restrictions 10498@subsection Use of Restrictions 10499 10500@noindent 10501The use of pragma Restrictions allows you to control which features are 10502permitted in your program. Apart from the obvious point that if you avoid 10503relatively expensive features like finalization (enforceable by the use 10504of pragma Restrictions (No_Finalization), the use of this pragma does not 10505affect the generated code in most cases. 10506 10507One notable exception to this rule is that the possibility of task abort 10508results in some distributed overhead, particularly if finalization or 10509exception handlers are used. The reason is that certain sections of code 10510have to be marked as non-abortable. 10511 10512If you use neither the @code{abort} statement, nor asynchronous transfer 10513of control (@code{select @dots{} then abort}), then this distributed overhead 10514is removed, which may have a general positive effect in improving 10515overall performance. Especially code involving frequent use of tasking 10516constructs and controlled types will show much improved performance. 10517The relevant restrictions pragmas are 10518 10519@smallexample @c ada 10520 pragma Restrictions (No_Abort_Statements); 10521 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0); 10522@end smallexample 10523 10524@noindent 10525It is recommended that these restriction pragmas be used if possible. Note 10526that this also means that you can write code without worrying about the 10527possibility of an immediate abort at any point. 10528 10529@node Optimization Levels 10530@subsection Optimization Levels 10531@cindex @option{^-O^/OPTIMIZE^} (@command{gcc}) 10532 10533@noindent 10534Without any optimization ^option,^qualifier,^ 10535the compiler's goal is to reduce the cost of 10536compilation and to make debugging produce the expected results. 10537Statements are independent: if you stop the program with a breakpoint between 10538statements, you can then assign a new value to any variable or change 10539the program counter to any other statement in the subprogram and get exactly 10540the results you would expect from the source code. 10541 10542Turning on optimization makes the compiler attempt to improve the 10543performance and/or code size at the expense of compilation time and 10544possibly the ability to debug the program. 10545 10546If you use multiple 10547^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^ 10548the last such option is the one that is effective. 10549 10550@noindent 10551The default is optimization off. This results in the fastest compile 10552times, but GNAT makes absolutely no attempt to optimize, and the 10553generated programs are considerably larger and slower than when 10554optimization is enabled. You can use the 10555@ifclear vms 10556@option{-O} switch (the permitted forms are @option{-O0}, @option{-O1} 10557@option{-O2}, @option{-O3}, and @option{-Os}) 10558@end ifclear 10559@ifset vms 10560@code{OPTIMIZE} qualifier 10561@end ifset 10562to @command{gcc} to control the optimization level: 10563 10564@table @option 10565@item ^-O0^/OPTIMIZE=NONE^ 10566No optimization (the default); 10567generates unoptimized code but has 10568the fastest compilation time. 10569 10570Note that many other compilers do fairly extensive optimization 10571even if ``no optimization'' is specified. With gcc, it is 10572very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if 10573execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^ 10574really does mean no optimization at all. This difference between 10575gcc and other compilers should be kept in mind when doing 10576performance comparisons. 10577 10578@item ^-O1^/OPTIMIZE=SOME^ 10579Moderate optimization; 10580optimizes reasonably well but does not 10581degrade compilation time significantly. 10582 10583@item ^-O2^/OPTIMIZE=ALL^ 10584@ifset vms 10585@itemx /OPTIMIZE=DEVELOPMENT 10586@end ifset 10587Full optimization; 10588generates highly optimized code and has 10589the slowest compilation time. 10590 10591@item ^-O3^/OPTIMIZE=INLINING^ 10592Full optimization as in @option{-O2}; 10593also uses more aggressive automatic inlining of subprograms within a unit 10594(@pxref{Inlining of Subprograms}) and attempts to vectorize loops. 10595 10596@item ^-Os^/OPTIMIZE=SPACE^ 10597Optimize space usage (code and data) of resulting program. 10598@end table 10599 10600@noindent 10601Higher optimization levels perform more global transformations on the 10602program and apply more expensive analysis algorithms in order to generate 10603faster and more compact code. The price in compilation time, and the 10604resulting improvement in execution time, 10605both depend on the particular application and the hardware environment. 10606You should experiment to find the best level for your application. 10607 10608Since the precise set of optimizations done at each level will vary from 10609release to release (and sometime from target to target), it is best to think 10610of the optimization settings in general terms. 10611@xref{Optimize Options,, Options That Control Optimization, gcc, Using 10612the GNU Compiler Collection (GCC)}, for details about 10613^the @option{-O} settings and a number of @option{-f} options that^how to^ 10614individually enable or disable specific optimizations. 10615 10616Unlike some other compilation systems, ^@command{gcc}^GNAT^ has 10617been tested extensively at all optimization levels. There are some bugs 10618which appear only with optimization turned on, but there have also been 10619bugs which show up only in @emph{unoptimized} code. Selecting a lower 10620level of optimization does not improve the reliability of the code 10621generator, which in practice is highly reliable at all optimization 10622levels. 10623 10624Note regarding the use of @option{-O3}: The use of this optimization level 10625is generally discouraged with GNAT, since it often results in larger 10626executables which may run more slowly. See further discussion of this point 10627in @ref{Inlining of Subprograms}. 10628 10629@node Debugging Optimized Code 10630@subsection Debugging Optimized Code 10631@cindex Debugging optimized code 10632@cindex Optimization and debugging 10633 10634@noindent 10635Although it is possible to do a reasonable amount of debugging at 10636@ifclear vms 10637nonzero optimization levels, 10638the higher the level the more likely that 10639@end ifclear 10640@ifset vms 10641@option{/OPTIMIZE} settings other than @code{NONE}, 10642such settings will make it more likely that 10643@end ifset 10644source-level constructs will have been eliminated by optimization. 10645For example, if a loop is strength-reduced, the loop 10646control variable may be completely eliminated and thus cannot be 10647displayed in the debugger. 10648This can only happen at @option{-O2} or @option{-O3}. 10649Explicit temporary variables that you code might be eliminated at 10650^level^setting^ @option{-O1} or higher. 10651 10652The use of the @option{^-g^/DEBUG^} switch, 10653@cindex @option{^-g^/DEBUG^} (@command{gcc}) 10654which is needed for source-level debugging, 10655affects the size of the program executable on disk, 10656and indeed the debugging information can be quite large. 10657However, it has no effect on the generated code (and thus does not 10658degrade performance) 10659 10660Since the compiler generates debugging tables for a compilation unit before 10661it performs optimizations, the optimizing transformations may invalidate some 10662of the debugging data. You therefore need to anticipate certain 10663anomalous situations that may arise while debugging optimized code. 10664These are the most common cases: 10665 10666@enumerate 10667@item 10668@i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next} 10669commands show 10670the PC bouncing back and forth in the code. This may result from any of 10671the following optimizations: 10672 10673@itemize @bullet 10674@item 10675@i{Common subexpression elimination:} using a single instance of code for a 10676quantity that the source computes several times. As a result you 10677may not be able to stop on what looks like a statement. 10678 10679@item 10680@i{Invariant code motion:} moving an expression that does not change within a 10681loop, to the beginning of the loop. 10682 10683@item 10684@i{Instruction scheduling:} moving instructions so as to 10685overlap loads and stores (typically) with other code, or in 10686general to move computations of values closer to their uses. Often 10687this causes you to pass an assignment statement without the assignment 10688happening and then later bounce back to the statement when the 10689value is actually needed. Placing a breakpoint on a line of code 10690and then stepping over it may, therefore, not always cause all the 10691expected side-effects. 10692@end itemize 10693 10694@item 10695@i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which 10696two identical pieces of code are merged and the program counter suddenly 10697jumps to a statement that is not supposed to be executed, simply because 10698it (and the code following) translates to the same thing as the code 10699that @emph{was} supposed to be executed. This effect is typically seen in 10700sequences that end in a jump, such as a @code{goto}, a @code{return}, or 10701a @code{break} in a C @code{^switch^switch^} statement. 10702 10703@item 10704@i{The ``roving variable'':} The symptom is an unexpected value in a variable. 10705There are various reasons for this effect: 10706 10707@itemize @bullet 10708@item 10709In a subprogram prologue, a parameter may not yet have been moved to its 10710``home''. 10711 10712@item 10713A variable may be dead, and its register re-used. This is 10714probably the most common cause. 10715 10716@item 10717As mentioned above, the assignment of a value to a variable may 10718have been moved. 10719 10720@item 10721A variable may be eliminated entirely by value propagation or 10722other means. In this case, GCC may incorrectly generate debugging 10723information for the variable 10724@end itemize 10725 10726@noindent 10727In general, when an unexpected value appears for a local variable or parameter 10728you should first ascertain if that value was actually computed by 10729your program, as opposed to being incorrectly reported by the debugger. 10730Record fields or 10731array elements in an object designated by an access value 10732are generally less of a problem, once you have ascertained that the access 10733value is sensible. 10734Typically, this means checking variables in the preceding code and in the 10735calling subprogram to verify that the value observed is explainable from other 10736values (one must apply the procedure recursively to those 10737other values); or re-running the code and stopping a little earlier 10738(perhaps before the call) and stepping to better see how the variable obtained 10739the value in question; or continuing to step @emph{from} the point of the 10740strange value to see if code motion had simply moved the variable's 10741assignments later. 10742@end enumerate 10743 10744@noindent 10745In light of such anomalies, a recommended technique is to use @option{-O0} 10746early in the software development cycle, when extensive debugging capabilities 10747are most needed, and then move to @option{-O1} and later @option{-O2} as 10748the debugger becomes less critical. 10749Whether to use the @option{^-g^/DEBUG^} switch in the release version is 10750a release management issue. 10751@ifclear vms 10752Note that if you use @option{-g} you can then use the @command{strip} program 10753on the resulting executable, 10754which removes both debugging information and global symbols. 10755@end ifclear 10756 10757@node Inlining of Subprograms 10758@subsection Inlining of Subprograms 10759 10760@noindent 10761A call to a subprogram in the current unit is inlined if all the 10762following conditions are met: 10763 10764@itemize @bullet 10765@item 10766The optimization level is at least @option{-O1}. 10767 10768@item 10769The called subprogram is suitable for inlining: It must be small enough 10770and not contain something that @command{gcc} cannot support in inlined 10771subprograms. 10772 10773@item 10774@cindex pragma Inline 10775@findex Inline 10776Any one of the following applies: @code{pragma Inline} is applied to the 10777subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the 10778subprogram is local to the unit and called once from within it; the 10779subprogram is small and optimization level @option{-O2} is specified; 10780optimization level @option{-O3} is specified. 10781@end itemize 10782 10783@noindent 10784Calls to subprograms in @code{with}'ed units are normally not inlined. 10785To achieve actual inlining (that is, replacement of the call by the code 10786in the body of the subprogram), the following conditions must all be true: 10787 10788@itemize @bullet 10789@item 10790The optimization level is at least @option{-O1}. 10791 10792@item 10793The called subprogram is suitable for inlining: It must be small enough 10794and not contain something that @command{gcc} cannot support in inlined 10795subprograms. 10796 10797@item 10798The call appears in a body (not in a package spec). 10799 10800@item 10801There is a @code{pragma Inline} for the subprogram. 10802 10803@item 10804The @option{^-gnatn^/INLINE^} switch is used on the command line. 10805@end itemize 10806 10807Even if all these conditions are met, it may not be possible for 10808the compiler to inline the call, due to the length of the body, 10809or features in the body that make it impossible for the compiler 10810to do the inlining. 10811 10812Note that specifying the @option{-gnatn} switch causes additional 10813compilation dependencies. Consider the following: 10814 10815@smallexample @c ada 10816@cartouche 10817package R is 10818 procedure Q; 10819 pragma Inline (Q); 10820end R; 10821package body R is 10822 @dots{} 10823end R; 10824 10825with R; 10826procedure Main is 10827begin 10828 @dots{} 10829 R.Q; 10830end Main; 10831@end cartouche 10832@end smallexample 10833 10834@noindent 10835With the default behavior (no @option{-gnatn} switch specified), the 10836compilation of the @code{Main} procedure depends only on its own source, 10837@file{main.adb}, and the spec of the package in file @file{r.ads}. This 10838means that editing the body of @code{R} does not require recompiling 10839@code{Main}. 10840 10841On the other hand, the call @code{R.Q} is not inlined under these 10842circumstances. If the @option{-gnatn} switch is present when @code{Main} 10843is compiled, the call will be inlined if the body of @code{Q} is small 10844enough, but now @code{Main} depends on the body of @code{R} in 10845@file{r.adb} as well as on the spec. This means that if this body is edited, 10846the main program must be recompiled. Note that this extra dependency 10847occurs whether or not the call is in fact inlined by @command{gcc}. 10848 10849The use of front end inlining with @option{-gnatN} generates similar 10850additional dependencies. 10851 10852@cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc}) 10853Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch 10854can be used to prevent 10855all inlining. This switch overrides all other conditions and ensures 10856that no inlining occurs. The extra dependences resulting from 10857@option{-gnatn} will still be active, even if 10858this switch is used to suppress the resulting inlining actions. 10859 10860@cindex @option{-fno-inline-functions} (@command{gcc}) 10861Note: The @option{-fno-inline-functions} switch can be used to prevent 10862automatic inlining of subprograms if @option{-O3} is used. 10863 10864@cindex @option{-fno-inline-small-functions} (@command{gcc}) 10865Note: The @option{-fno-inline-small-functions} switch can be used to prevent 10866automatic inlining of small subprograms if @option{-O2} is used. 10867 10868@cindex @option{-fno-inline-functions-called-once} (@command{gcc}) 10869Note: The @option{-fno-inline-functions-called-once} switch 10870can be used to prevent inlining of subprograms local to the unit 10871and called once from within it if @option{-O1} is used. 10872 10873Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two 10874sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly 10875specified in lieu of it, @option{-gnatn} being translated into one of them 10876based on the optimization level. With @option{-O2} or below, @option{-gnatn} 10877is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with 10878moderate inlining across modules. With @option{-O3}, @option{-gnatn} is 10879equivalent to @option{-gnatn2} which activates pragma @code{Inline} with 10880full inlining across modules. If you have used pragma @code{Inline} in appropriate cases, then it is usually much better to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which has the additional 10881effect of inlining subprograms you did not think should be inlined. We have 10882found that the use of @option{-O3} may slow down the compilation and increase 10883the code size by performing excessive inlining, leading to increased 10884instruction cache pressure from the increased code size and thus minor 10885performance improvements. So the bottom line here is that you should not 10886automatically assume that @option{-O3} is better than @option{-O2}, and 10887indeed you should use @option{-O3} only if tests show that it actually 10888improves performance for your program. 10889 10890@node Vectorization of loops 10891@subsection Vectorization of loops 10892@cindex Optimization Switches 10893 10894You can take advantage of the auto-vectorizer present in the @command{gcc} 10895back end to vectorize loops with GNAT. The corresponding command line switch 10896is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3} 10897and other aggressive optimizations helpful for vectorization also are enabled 10898by default at this level, using @option{-O3} directly is recommended. 10899 10900You also need to make sure that the target architecture features a supported 10901SIMD instruction set. For example, for the x86 architecture, you should at 10902least specify @option{-msse2} to get significant vectorization (but you don't 10903need to specify it for x86-64 as it is part of the base 64-bit architecture). 10904Similarly, for the PowerPC architecture, you should specify @option{-maltivec}. 10905 10906The preferred loop form for vectorization is the @code{for} iteration scheme. 10907Loops with a @code{while} iteration scheme can also be vectorized if they are 10908very simple, but the vectorizer will quickly give up otherwise. With either 10909iteration scheme, the flow of control must be straight, in particular no 10910@code{exit} statement may appear in the loop body. The loop may however 10911contain a single nested loop, if it can be vectorized when considered alone: 10912 10913@smallexample @c ada 10914@cartouche 10915 A : array (1..4, 1..4) of Long_Float; 10916 S : array (1..4) of Long_Float; 10917 10918 procedure Sum is 10919 begin 10920 for I in A'Range(1) loop 10921 for J in A'Range(2) loop 10922 S (I) := S (I) + A (I, J); 10923 end loop; 10924 end loop; 10925 end Sum; 10926@end cartouche 10927@end smallexample 10928 10929The vectorizable operations depend on the targeted SIMD instruction set, but 10930the adding and some of the multiplying operators are generally supported, as 10931well as the logical operators for modular types. Note that, in the former 10932case, enabling overflow checks, for example with @option{-gnato}, totally 10933disables vectorization. The other checks are not supposed to have the same 10934definitive effect, although compiling with @option{-gnatp} might well reveal 10935cases where some checks do thwart vectorization. 10936 10937Type conversions may also prevent vectorization if they involve semantics that 10938are not directly supported by the code generator or the SIMD instruction set. 10939A typical example is direct conversion from floating-point to integer types. 10940The solution in this case is to use the following idiom: 10941 10942@smallexample @c ada 10943 Integer (S'Truncation (F)) 10944@end smallexample 10945 10946@noindent 10947if @code{S} is the subtype of floating-point object @code{F}. 10948 10949In most cases, the vectorizable loops are loops that iterate over arrays. 10950All kinds of array types are supported, i.e. constrained array types with 10951static bounds: 10952 10953@smallexample @c ada 10954 type Array_Type is array (1 .. 4) of Long_Float; 10955@end smallexample 10956 10957@noindent 10958constrained array types with dynamic bounds: 10959 10960@smallexample @c ada 10961 type Array_Type is array (1 .. Q.N) of Long_Float; 10962 10963 type Array_Type is array (Q.K .. 4) of Long_Float; 10964 10965 type Array_Type is array (Q.K .. Q.N) of Long_Float; 10966@end smallexample 10967 10968@noindent 10969or unconstrained array types: 10970 10971@smallexample @c ada 10972 type Array_Type is array (Positive range <>) of Long_Float; 10973@end smallexample 10974 10975@noindent 10976The quality of the generated code decreases when the dynamic aspect of the 10977array type increases, the worst code being generated for unconstrained array 10978types. This is so because, the less information the compiler has about the 10979bounds of the array, the more fallback code it needs to generate in order to 10980fix things up at run time. 10981 10982It is possible to specify that a given loop should be subject to vectorization 10983preferably to other optimizations by means of pragma @code{Loop_Optimize}: 10984 10985@smallexample @c ada 10986 pragma Loop_Optimize (Vector); 10987@end smallexample 10988 10989@noindent 10990placed immediately within the loop will convey the appropriate hint to the 10991compiler for this loop. 10992 10993You can obtain information about the vectorization performed by the compiler 10994by specifying @option{-ftree-vectorizer-verbose=N}. For more details of 10995this switch, see @ref{Debugging Options,,Options for Debugging Your Program 10996or GCC, gcc, Using the GNU Compiler Collection (GCC)}. 10997 10998@node Other Optimization Switches 10999@subsection Other Optimization Switches 11000@cindex Optimization Switches 11001 11002Since @code{GNAT} uses the @command{gcc} back end, all the specialized 11003@command{gcc} optimization switches are potentially usable. These switches 11004have not been extensively tested with GNAT but can generally be expected 11005to work. Examples of switches in this category are @option{-funroll-loops} 11006and the various target-specific @option{-m} options (in particular, it has 11007been observed that @option{-march=xxx} can significantly improve performance 11008on appropriate machines). For full details of these switches, see 11009@ref{Submodel Options,, Hardware Models and Configurations, gcc, Using 11010the GNU Compiler Collection (GCC)}. 11011 11012@node Optimization and Strict Aliasing 11013@subsection Optimization and Strict Aliasing 11014@cindex Aliasing 11015@cindex Strict Aliasing 11016@cindex No_Strict_Aliasing 11017 11018@noindent 11019The strong typing capabilities of Ada allow an optimizer to generate 11020efficient code in situations where other languages would be forced to 11021make worst case assumptions preventing such optimizations. Consider 11022the following example: 11023 11024@smallexample @c ada 11025@cartouche 11026procedure R is 11027 type Int1 is new Integer; 11028 type Int2 is new Integer; 11029 type Int1A is access Int1; 11030 type Int2A is access Int2; 11031 Int1V : Int1A; 11032 Int2V : Int2A; 11033 @dots{} 11034 11035begin 11036 @dots{} 11037 for J in Data'Range loop 11038 if Data (J) = Int1V.all then 11039 Int2V.all := Int2V.all + 1; 11040 end if; 11041 end loop; 11042 @dots{} 11043end R; 11044@end cartouche 11045@end smallexample 11046 11047@noindent 11048In this example, since the variable @code{Int1V} can only access objects 11049of type @code{Int1}, and @code{Int2V} can only access objects of type 11050@code{Int2}, there is no possibility that the assignment to 11051@code{Int2V.all} affects the value of @code{Int1V.all}. This means that 11052the compiler optimizer can "know" that the value @code{Int1V.all} is constant 11053for all iterations of the loop and avoid the extra memory reference 11054required to dereference it each time through the loop. 11055 11056This kind of optimization, called strict aliasing analysis, is 11057triggered by specifying an optimization level of @option{-O2} or 11058higher or @option{-Os} and allows @code{GNAT} to generate more efficient code 11059when access values are involved. 11060 11061However, although this optimization is always correct in terms of 11062the formal semantics of the Ada Reference Manual, difficulties can 11063arise if features like @code{Unchecked_Conversion} are used to break 11064the typing system. Consider the following complete program example: 11065 11066@smallexample @c ada 11067@cartouche 11068package p1 is 11069 type int1 is new integer; 11070 type int2 is new integer; 11071 type a1 is access int1; 11072 type a2 is access int2; 11073end p1; 11074 11075with p1; use p1; 11076package p2 is 11077 function to_a2 (Input : a1) return a2; 11078end p2; 11079 11080with Unchecked_Conversion; 11081package body p2 is 11082 function to_a2 (Input : a1) return a2 is 11083 function to_a2u is 11084 new Unchecked_Conversion (a1, a2); 11085 begin 11086 return to_a2u (Input); 11087 end to_a2; 11088end p2; 11089 11090with p2; use p2; 11091with p1; use p1; 11092with Text_IO; use Text_IO; 11093procedure m is 11094 v1 : a1 := new int1; 11095 v2 : a2 := to_a2 (v1); 11096begin 11097 v1.all := 1; 11098 v2.all := 0; 11099 put_line (int1'image (v1.all)); 11100end; 11101@end cartouche 11102@end smallexample 11103 11104@noindent 11105This program prints out 0 in @option{-O0} or @option{-O1} 11106mode, but it prints out 1 in @option{-O2} mode. That's 11107because in strict aliasing mode, the compiler can and 11108does assume that the assignment to @code{v2.all} could not 11109affect the value of @code{v1.all}, since different types 11110are involved. 11111 11112This behavior is not a case of non-conformance with the standard, since 11113the Ada RM specifies that an unchecked conversion where the resulting 11114bit pattern is not a correct value of the target type can result in an 11115abnormal value and attempting to reference an abnormal value makes the 11116execution of a program erroneous. That's the case here since the result 11117does not point to an object of type @code{int2}. This means that the 11118effect is entirely unpredictable. 11119 11120However, although that explanation may satisfy a language 11121lawyer, in practice an applications programmer expects an 11122unchecked conversion involving pointers to create true 11123aliases and the behavior of printing 1 seems plain wrong. 11124In this case, the strict aliasing optimization is unwelcome. 11125 11126Indeed the compiler recognizes this possibility, and the 11127unchecked conversion generates a warning: 11128 11129@smallexample 11130p2.adb:5:07: warning: possible aliasing problem with type "a2" 11131p2.adb:5:07: warning: use -fno-strict-aliasing switch for references 11132p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);" 11133@end smallexample 11134 11135@noindent 11136Unfortunately the problem is recognized when compiling the body of 11137package @code{p2}, but the actual "bad" code is generated while 11138compiling the body of @code{m} and this latter compilation does not see 11139the suspicious @code{Unchecked_Conversion}. 11140 11141As implied by the warning message, there are approaches you can use to 11142avoid the unwanted strict aliasing optimization in a case like this. 11143 11144One possibility is to simply avoid the use of @option{-O2}, but 11145that is a bit drastic, since it throws away a number of useful 11146optimizations that do not involve strict aliasing assumptions. 11147 11148A less drastic approach is to compile the program using the 11149option @option{-fno-strict-aliasing}. Actually it is only the 11150unit containing the dereferencing of the suspicious pointer 11151that needs to be compiled. So in this case, if we compile 11152unit @code{m} with this switch, then we get the expected 11153value of zero printed. Analyzing which units might need 11154the switch can be painful, so a more reasonable approach 11155is to compile the entire program with options @option{-O2} 11156and @option{-fno-strict-aliasing}. If the performance is 11157satisfactory with this combination of options, then the 11158advantage is that the entire issue of possible "wrong" 11159optimization due to strict aliasing is avoided. 11160 11161To avoid the use of compiler switches, the configuration 11162pragma @code{No_Strict_Aliasing} with no parameters may be 11163used to specify that for all access types, the strict 11164aliasing optimization should be suppressed. 11165 11166However, these approaches are still overkill, in that they causes 11167all manipulations of all access values to be deoptimized. A more 11168refined approach is to concentrate attention on the specific 11169access type identified as problematic. 11170 11171First, if a careful analysis of uses of the pointer shows 11172that there are no possible problematic references, then 11173the warning can be suppressed by bracketing the 11174instantiation of @code{Unchecked_Conversion} to turn 11175the warning off: 11176 11177@smallexample @c ada 11178 pragma Warnings (Off); 11179 function to_a2u is 11180 new Unchecked_Conversion (a1, a2); 11181 pragma Warnings (On); 11182@end smallexample 11183 11184@noindent 11185Of course that approach is not appropriate for this particular 11186example, since indeed there is a problematic reference. In this 11187case we can take one of two other approaches. 11188 11189The first possibility is to move the instantiation of unchecked 11190conversion to the unit in which the type is declared. In 11191this example, we would move the instantiation of 11192@code{Unchecked_Conversion} from the body of package 11193@code{p2} to the spec of package @code{p1}. Now the 11194warning disappears. That's because any use of the 11195access type knows there is a suspicious unchecked 11196conversion, and the strict aliasing optimization 11197is automatically suppressed for the type. 11198 11199If it is not practical to move the unchecked conversion to the same unit 11200in which the destination access type is declared (perhaps because the 11201source type is not visible in that unit), you may use pragma 11202@code{No_Strict_Aliasing} for the type. This pragma must occur in the 11203same declarative sequence as the declaration of the access type: 11204 11205@smallexample @c ada 11206 type a2 is access int2; 11207 pragma No_Strict_Aliasing (a2); 11208@end smallexample 11209 11210@noindent 11211Here again, the compiler now knows that the strict aliasing optimization 11212should be suppressed for any reference to type @code{a2} and the 11213expected behavior is obtained. 11214 11215Finally, note that although the compiler can generate warnings for 11216simple cases of unchecked conversions, there are tricker and more 11217indirect ways of creating type incorrect aliases which the compiler 11218cannot detect. Examples are the use of address overlays and unchecked 11219conversions involving composite types containing access types as 11220components. In such cases, no warnings are generated, but there can 11221still be aliasing problems. One safe coding practice is to forbid the 11222use of address clauses for type overlaying, and to allow unchecked 11223conversion only for primitive types. This is not really a significant 11224restriction since any possible desired effect can be achieved by 11225unchecked conversion of access values. 11226 11227The aliasing analysis done in strict aliasing mode can certainly 11228have significant benefits. We have seen cases of large scale 11229application code where the time is increased by up to 5% by turning 11230this optimization off. If you have code that includes significant 11231usage of unchecked conversion, you might want to just stick with 11232@option{-O1} and avoid the entire issue. If you get adequate 11233performance at this level of optimization level, that's probably 11234the safest approach. If tests show that you really need higher 11235levels of optimization, then you can experiment with @option{-O2} 11236and @option{-O2 -fno-strict-aliasing} to see how much effect this 11237has on size and speed of the code. If you really need to use 11238@option{-O2} with strict aliasing in effect, then you should 11239review any uses of unchecked conversion of access types, 11240particularly if you are getting the warnings described above. 11241 11242@ifset vms 11243@node Coverage Analysis 11244@subsection Coverage Analysis 11245 11246@noindent 11247GNAT supports the HP Performance Coverage Analyzer (PCA), which allows 11248the user to determine the distribution of execution time across a program, 11249@pxref{Profiling} for details of usage. 11250@end ifset 11251 11252 11253@node Text_IO Suggestions 11254@section @code{Text_IO} Suggestions 11255@cindex @code{Text_IO} and performance 11256 11257@noindent 11258The @code{Ada.Text_IO} package has fairly high overheads due in part to 11259the requirement of maintaining page and line counts. If performance 11260is critical, a recommendation is to use @code{Stream_IO} instead of 11261@code{Text_IO} for volume output, since this package has less overhead. 11262 11263If @code{Text_IO} must be used, note that by default output to the standard 11264output and standard error files is unbuffered (this provides better 11265behavior when output statements are used for debugging, or if the 11266progress of a program is observed by tracking the output, e.g. by 11267using the Unix @command{tail -f} command to watch redirected output. 11268 11269If you are generating large volumes of output with @code{Text_IO} and 11270performance is an important factor, use a designated file instead 11271of the standard output file, or change the standard output file to 11272be buffered using @code{Interfaces.C_Streams.setvbuf}. 11273 11274 11275 11276@node Reducing Size of Ada Executables with gnatelim 11277@section Reducing Size of Ada Executables with @code{gnatelim} 11278@findex gnatelim 11279 11280@noindent 11281This section describes @command{gnatelim}, a tool which detects unused 11282subprograms and helps the compiler to create a smaller executable for your 11283program. 11284 11285@menu 11286* About gnatelim:: 11287* Running gnatelim:: 11288* Processing Precompiled Libraries:: 11289* Correcting the List of Eliminate Pragmas:: 11290* Making Your Executables Smaller:: 11291* Summary of the gnatelim Usage Cycle:: 11292@end menu 11293 11294@node About gnatelim 11295@subsection About @code{gnatelim} 11296 11297@noindent 11298When a program shares a set of Ada 11299packages with other programs, it may happen that this program uses 11300only a fraction of the subprograms defined in these packages. The code 11301created for these unused subprograms increases the size of the executable. 11302 11303@code{gnatelim} tracks unused subprograms in an Ada program and 11304outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the 11305subprograms that are declared but never called. By placing the list of 11306@code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and 11307recompiling your program, you may decrease the size of its executable, 11308because the compiler will not generate the code for 'eliminated' subprograms. 11309@xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more 11310information about this pragma. 11311 11312@code{gnatelim} needs as its input data the name of the main subprogram. 11313 11314If a set of source files is specified as @code{gnatelim} arguments, it 11315treats these files as a complete set of sources making up a program to 11316analyse, and analyses only these sources. 11317 11318After a full successful build of the main subprogram @code{gnatelim} can be 11319called without specifying sources to analyse, in this case it computes 11320the source closure of the main unit from the @file{ALI} files. 11321 11322The following command will create the set of @file{ALI} files needed for 11323@code{gnatelim}: 11324 11325@smallexample 11326$ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^ 11327@end smallexample 11328 11329Note that @code{gnatelim} does not need object files. 11330 11331@node Running gnatelim 11332@subsection Running @code{gnatelim} 11333 11334@noindent 11335@code{gnatelim} has the following command-line interface: 11336 11337@smallexample 11338$ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]} 11339@end smallexample 11340 11341@noindent 11342@var{main_unit_name} should be a name of a source file that contains the main 11343subprogram of a program (partition). 11344 11345Each @var{filename} is the name (including the extension) of a source 11346file to process. ``Wildcards'' are allowed, and 11347the file name may contain path information. 11348 11349@samp{@var{gcc_switches}} is a list of switches for 11350@command{gcc}. They will be passed on to all compiler invocations made by 11351@command{gnatelim} to generate the ASIS trees. Here you can provide 11352@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path, 11353use the @option{-gnatec} switch to set the configuration file, 11354use the @option{-gnat05} switch if sources should be compiled in 11355Ada 2005 mode etc. 11356 11357@code{gnatelim} has the following switches: 11358 11359@table @option 11360@c !sort! 11361@item ^-files^/FILES^=@var{filename} 11362@cindex @option{^-files^/FILES^} (@code{gnatelim}) 11363Take the argument source files from the specified file. This file should be an 11364ordinary text file containing file names separated by spaces or 11365line breaks. You can use this switch more than once in the same call to 11366@command{gnatelim}. You also can combine this switch with 11367an explicit list of files. 11368 11369@item ^-log^/LOG^ 11370@cindex @option{^-log^/LOG^} (@command{gnatelim}) 11371Duplicate all the output sent to @file{stderr} into a log file. The log file 11372is named @file{gnatelim.log} and is located in the current directory. 11373 11374@item ^-log^/LOGFILE^=@var{filename} 11375@cindex @option{^-log^/LOGFILE^} (@command{gnatelim}) 11376Duplicate all the output sent to @file{stderr} into a specified log file. 11377 11378@cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim}) 11379@item ^--no-elim-dispatch^/NO_DISPATCH^ 11380Do not generate pragmas for dispatching operations. 11381 11382@item ^--ignore^/IGNORE^=@var{filename} 11383@cindex @option{^--ignore^/IGNORE^} (@command{gnatelim}) 11384Do not generate pragmas for subprograms declared in the sources 11385listed in a specified file 11386 11387@cindex @option{^-o^/OUTPUT^} (@command{gnatelim}) 11388@item ^-o^/OUTPUT^=@var{report_file} 11389Put @command{gnatelim} output into a specified file. If this file already exists, 11390it is overridden. If this switch is not used, @command{gnatelim} outputs its results 11391into @file{stderr} 11392 11393@item ^-q^/QUIET^ 11394@cindex @option{^-q^/QUIET^} (@command{gnatelim}) 11395Quiet mode: by default @code{gnatelim} outputs to the standard error 11396stream the number of program units left to be processed. This option turns 11397this trace off. 11398 11399@cindex @option{^-t^/TIME^} (@command{gnatelim}) 11400@item ^-t^/TIME^ 11401Print out execution time. 11402 11403@item ^-v^/VERBOSE^ 11404@cindex @option{^-v^/VERBOSE^} (@command{gnatelim}) 11405Verbose mode: @code{gnatelim} version information is printed as Ada 11406comments to the standard output stream. Also, in addition to the number of 11407program units left @code{gnatelim} will output the name of the current unit 11408being processed. 11409 11410@item ^-wq^/WARNINGS=QUIET^ 11411@cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim}) 11412Quiet warning mode - some warnings are suppressed. In particular warnings that 11413indicate that the analysed set of sources is incomplete to make up a 11414partition and that some subprogram bodies are missing are not generated. 11415@end table 11416 11417@noindent 11418Note: to invoke @command{gnatelim} with a project file, use the @code{gnat} 11419driver (see @ref{The GNAT Driver and Project Files}). 11420 11421@node Processing Precompiled Libraries 11422@subsection Processing Precompiled Libraries 11423 11424@noindent 11425If some program uses a precompiled Ada library, it can be processed by 11426@code{gnatelim} in a usual way. @code{gnatelim} will newer generate an 11427Eliminate pragma for a subprogram if the body of this subprogram has not 11428been analysed, this is a typical case for subprograms from precompiled 11429libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress 11430warnings about missing source files and non-analyzed subprogram bodies 11431that can be generated when processing precompiled Ada libraries. 11432 11433@node Correcting the List of Eliminate Pragmas 11434@subsection Correcting the List of Eliminate Pragmas 11435 11436@noindent 11437In some rare cases @code{gnatelim} may try to eliminate 11438subprograms that are actually called in the program. In this case, the 11439compiler will generate an error message of the form: 11440 11441@smallexample 11442main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5 11443@end smallexample 11444 11445@noindent 11446You will need to manually remove the wrong @code{Eliminate} pragmas from 11447the configuration file indicated in the error message. You should recompile 11448your program from scratch after that, because you need a consistent 11449configuration file(s) during the entire compilation. 11450 11451@node Making Your Executables Smaller 11452@subsection Making Your Executables Smaller 11453 11454@noindent 11455In order to get a smaller executable for your program you now have to 11456recompile the program completely with the configuration file containing 11457pragmas Eliminate generated by gnatelim. If these pragmas are placed in 11458@file{gnat.adc} file located in your current directory, just do: 11459 11460@smallexample 11461$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^ 11462@end smallexample 11463 11464@noindent 11465(Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to 11466recompile everything 11467with the set of pragmas @code{Eliminate} that you have obtained with 11468@command{gnatelim}). 11469 11470Be aware that the set of @code{Eliminate} pragmas is specific to each 11471program. It is not recommended to merge sets of @code{Eliminate} 11472pragmas created for different programs in one configuration file. 11473 11474@node Summary of the gnatelim Usage Cycle 11475@subsection Summary of the @code{gnatelim} Usage Cycle 11476 11477@noindent 11478Here is a quick summary of the steps to be taken in order to reduce 11479the size of your executables with @code{gnatelim}. You may use 11480other GNAT options to control the optimization level, 11481to produce the debugging information, to set search path, etc. 11482 11483@enumerate 11484@item 11485Create a complete set of @file{ALI} files (if the program has not been 11486built already) 11487 11488@smallexample 11489$ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^ 11490@end smallexample 11491 11492@item 11493Generate a list of @code{Eliminate} pragmas in default configuration file 11494@file{gnat.adc} in the current directory 11495@smallexample 11496@ifset vms 11497$ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC 11498@end ifset 11499@ifclear vms 11500$ gnatelim main_prog >@r{[}>@r{]} gnat.adc 11501@end ifclear 11502@end smallexample 11503 11504@item 11505Recompile the application 11506 11507@smallexample 11508$ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^ 11509@end smallexample 11510 11511@end enumerate 11512 11513@node Reducing Size of Executables with unused subprogram/data elimination 11514@section Reducing Size of Executables with Unused Subprogram/Data Elimination 11515@findex unused subprogram/data elimination 11516 11517@noindent 11518This section describes how you can eliminate unused subprograms and data from 11519your executable just by setting options at compilation time. 11520 11521@menu 11522* About unused subprogram/data elimination:: 11523* Compilation options:: 11524* Example of unused subprogram/data elimination:: 11525@end menu 11526 11527@node About unused subprogram/data elimination 11528@subsection About unused subprogram/data elimination 11529 11530@noindent 11531By default, an executable contains all code and data of its composing objects 11532(directly linked or coming from statically linked libraries), even data or code 11533never used by this executable. 11534 11535This feature will allow you to eliminate such unused code from your 11536executable, making it smaller (in disk and in memory). 11537 11538This functionality is available on all Linux platforms except for the IA-64 11539architecture and on all cross platforms using the ELF binary file format. 11540In both cases GNU binutils version 2.16 or later are required to enable it. 11541 11542@node Compilation options 11543@subsection Compilation options 11544 11545@noindent 11546The operation of eliminating the unused code and data from the final executable 11547is directly performed by the linker. 11548 11549In order to do this, it has to work with objects compiled with the 11550following options: 11551@option{-ffunction-sections} @option{-fdata-sections}. 11552@cindex @option{-ffunction-sections} (@command{gcc}) 11553@cindex @option{-fdata-sections} (@command{gcc}) 11554These options are usable with C and Ada files. 11555They will place respectively each 11556function or data in a separate section in the resulting object file. 11557 11558Once the objects and static libraries are created with these options, the 11559linker can perform the dead code elimination. You can do this by setting 11560the @option{-Wl,--gc-sections} option to gcc command or in the 11561@option{-largs} section of @command{gnatmake}. This will perform a 11562garbage collection of code and data never referenced. 11563 11564If the linker performs a partial link (@option{-r} ld linker option), then you 11565will need to provide one or several entry point using the 11566@option{-e} / @option{--entry} ld option. 11567 11568Note that objects compiled without the @option{-ffunction-sections} and 11569@option{-fdata-sections} options can still be linked with the executable. 11570However, no dead code elimination will be performed on those objects (they will 11571be linked as is). 11572 11573The GNAT static library is now compiled with -ffunction-sections and 11574-fdata-sections on some platforms. This allows you to eliminate the unused code 11575and data of the GNAT library from your executable. 11576 11577@node Example of unused subprogram/data elimination 11578@subsection Example of unused subprogram/data elimination 11579 11580@noindent 11581Here is a simple example: 11582 11583@smallexample @c ada 11584with Aux; 11585 11586procedure Test is 11587begin 11588 Aux.Used (10); 11589end Test; 11590 11591package Aux is 11592 Used_Data : Integer; 11593 Unused_Data : Integer; 11594 11595 procedure Used (Data : Integer); 11596 procedure Unused (Data : Integer); 11597end Aux; 11598 11599package body Aux is 11600 procedure Used (Data : Integer) is 11601 begin 11602 Used_Data := Data; 11603 end Used; 11604 11605 procedure Unused (Data : Integer) is 11606 begin 11607 Unused_Data := Data; 11608 end Unused; 11609end Aux; 11610@end smallexample 11611 11612@noindent 11613@code{Unused} and @code{Unused_Data} are never referenced in this code 11614excerpt, and hence they may be safely removed from the final executable. 11615 11616@smallexample 11617$ gnatmake test 11618 11619$ nm test | grep used 11620020015f0 T aux__unused 1162102005d88 B aux__unused_data 11622020015cc T aux__used 1162302005d84 B aux__used_data 11624 11625$ gnatmake test -cargs -fdata-sections -ffunction-sections \ 11626 -largs -Wl,--gc-sections 11627 11628$ nm test | grep used 1162902005350 T aux__used 116300201ffe0 B aux__used_data 11631@end smallexample 11632 11633@noindent 11634It can be observed that the procedure @code{Unused} and the object 11635@code{Unused_Data} are removed by the linker when using the 11636appropriate options. 11637 11638@c ******************************** 11639@node Renaming Files Using gnatchop 11640@chapter Renaming Files Using @code{gnatchop} 11641@findex gnatchop 11642 11643@noindent 11644This chapter discusses how to handle files with multiple units by using 11645the @code{gnatchop} utility. This utility is also useful in renaming 11646files to meet the standard GNAT default file naming conventions. 11647 11648@menu 11649* Handling Files with Multiple Units:: 11650* Operating gnatchop in Compilation Mode:: 11651* Command Line for gnatchop:: 11652* Switches for gnatchop:: 11653* Examples of gnatchop Usage:: 11654@end menu 11655 11656@node Handling Files with Multiple Units 11657@section Handling Files with Multiple Units 11658 11659@noindent 11660The basic compilation model of GNAT requires that a file submitted to the 11661compiler have only one unit and there be a strict correspondence 11662between the file name and the unit name. 11663 11664The @code{gnatchop} utility allows both of these rules to be relaxed, 11665allowing GNAT to process files which contain multiple compilation units 11666and files with arbitrary file names. @code{gnatchop} 11667reads the specified file and generates one or more output files, 11668containing one unit per file. The unit and the file name correspond, 11669as required by GNAT. 11670 11671If you want to permanently restructure a set of ``foreign'' files so that 11672they match the GNAT rules, and do the remaining development using the 11673GNAT structure, you can simply use @command{gnatchop} once, generate the 11674new set of files and work with them from that point on. 11675 11676Alternatively, if you want to keep your files in the ``foreign'' format, 11677perhaps to maintain compatibility with some other Ada compilation 11678system, you can set up a procedure where you use @command{gnatchop} each 11679time you compile, regarding the source files that it writes as temporary 11680files that you throw away. 11681 11682Note that if your file containing multiple units starts with a byte order 11683mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop 11684will each start with a copy of this BOM, meaning that they can be compiled 11685automatically in UTF-8 mode without needing to specify an explicit encoding. 11686 11687@node Operating gnatchop in Compilation Mode 11688@section Operating gnatchop in Compilation Mode 11689 11690@noindent 11691The basic function of @code{gnatchop} is to take a file with multiple units 11692and split it into separate files. The boundary between files is reasonably 11693clear, except for the issue of comments and pragmas. In default mode, the 11694rule is that any pragmas between units belong to the previous unit, except 11695that configuration pragmas always belong to the following unit. Any comments 11696belong to the following unit. These rules 11697almost always result in the right choice of 11698the split point without needing to mark it explicitly and most users will 11699find this default to be what they want. In this default mode it is incorrect to 11700submit a file containing only configuration pragmas, or one that ends in 11701configuration pragmas, to @code{gnatchop}. 11702 11703However, using a special option to activate ``compilation mode'', 11704@code{gnatchop} 11705can perform another function, which is to provide exactly the semantics 11706required by the RM for handling of configuration pragmas in a compilation. 11707In the absence of configuration pragmas (at the main file level), this 11708option has no effect, but it causes such configuration pragmas to be handled 11709in a quite different manner. 11710 11711First, in compilation mode, if @code{gnatchop} is given a file that consists of 11712only configuration pragmas, then this file is appended to the 11713@file{gnat.adc} file in the current directory. This behavior provides 11714the required behavior described in the RM for the actions to be taken 11715on submitting such a file to the compiler, namely that these pragmas 11716should apply to all subsequent compilations in the same compilation 11717environment. Using GNAT, the current directory, possibly containing a 11718@file{gnat.adc} file is the representation 11719of a compilation environment. For more information on the 11720@file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}. 11721 11722Second, in compilation mode, if @code{gnatchop} 11723is given a file that starts with 11724configuration pragmas, and contains one or more units, then these 11725configuration pragmas are prepended to each of the chopped files. This 11726behavior provides the required behavior described in the RM for the 11727actions to be taken on compiling such a file, namely that the pragmas 11728apply to all units in the compilation, but not to subsequently compiled 11729units. 11730 11731Finally, if configuration pragmas appear between units, they are appended 11732to the previous unit. This results in the previous unit being illegal, 11733since the compiler does not accept configuration pragmas that follow 11734a unit. This provides the required RM behavior that forbids configuration 11735pragmas other than those preceding the first compilation unit of a 11736compilation. 11737 11738For most purposes, @code{gnatchop} will be used in default mode. The 11739compilation mode described above is used only if you need exactly 11740accurate behavior with respect to compilations, and you have files 11741that contain multiple units and configuration pragmas. In this 11742circumstance the use of @code{gnatchop} with the compilation mode 11743switch provides the required behavior, and is for example the mode 11744in which GNAT processes the ACVC tests. 11745 11746@node Command Line for gnatchop 11747@section Command Line for @code{gnatchop} 11748 11749@noindent 11750The @code{gnatchop} command has the form: 11751 11752@smallexample 11753@c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]} 11754@c @ovar{directory} 11755@c Expanding @ovar macro inline (explanation in macro def comments) 11756$ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]} 11757 @r{[}@var{directory}@r{]} 11758@end smallexample 11759 11760@noindent 11761The only required argument is the file name of the file to be chopped. 11762There are no restrictions on the form of this file name. The file itself 11763contains one or more Ada units, in normal GNAT format, concatenated 11764together. As shown, more than one file may be presented to be chopped. 11765 11766When run in default mode, @code{gnatchop} generates one output file in 11767the current directory for each unit in each of the files. 11768 11769@var{directory}, if specified, gives the name of the directory to which 11770the output files will be written. If it is not specified, all files are 11771written to the current directory. 11772 11773For example, given a 11774file called @file{hellofiles} containing 11775 11776@smallexample @c ada 11777@group 11778@cartouche 11779procedure hello; 11780 11781with Text_IO; use Text_IO; 11782procedure hello is 11783begin 11784 Put_Line ("Hello"); 11785end hello; 11786@end cartouche 11787@end group 11788@end smallexample 11789 11790@noindent 11791the command 11792 11793@smallexample 11794$ gnatchop ^hellofiles^HELLOFILES.^ 11795@end smallexample 11796 11797@noindent 11798generates two files in the current directory, one called 11799@file{hello.ads} containing the single line that is the procedure spec, 11800and the other called @file{hello.adb} containing the remaining text. The 11801original file is not affected. The generated files can be compiled in 11802the normal manner. 11803 11804@noindent 11805When gnatchop is invoked on a file that is empty or that contains only empty 11806lines and/or comments, gnatchop will not fail, but will not produce any 11807new sources. 11808 11809For example, given a 11810file called @file{toto.txt} containing 11811 11812@smallexample @c ada 11813@group 11814@cartouche 11815-- Just a comment 11816@end cartouche 11817@end group 11818@end smallexample 11819 11820@noindent 11821the command 11822 11823@smallexample 11824$ gnatchop ^toto.txt^TOT.TXT^ 11825@end smallexample 11826 11827@noindent 11828will not produce any new file and will result in the following warnings: 11829 11830@smallexample 11831toto.txt:1:01: warning: empty file, contains no compilation units 11832no compilation units found 11833no source files written 11834@end smallexample 11835 11836@node Switches for gnatchop 11837@section Switches for @code{gnatchop} 11838 11839@noindent 11840@command{gnatchop} recognizes the following switches: 11841 11842@table @option 11843@c !sort! 11844 11845@item --version 11846@cindex @option{--version} @command{gnatchop} 11847Display Copyright and version, then exit disregarding all other options. 11848 11849@item --help 11850@cindex @option{--help} @command{gnatchop} 11851If @option{--version} was not used, display usage, then exit disregarding 11852all other options. 11853 11854@item ^-c^/COMPILATION^ 11855@cindex @option{^-c^/COMPILATION^} (@code{gnatchop}) 11856Causes @code{gnatchop} to operate in compilation mode, in which 11857configuration pragmas are handled according to strict RM rules. See 11858previous section for a full description of this mode. 11859 11860@ifclear vms 11861@item -gnat@var{xxx} 11862This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is 11863used to parse the given file. Not all @var{xxx} options make sense, 11864but for example, the use of @option{-gnati2} allows @code{gnatchop} to 11865process a source file that uses Latin-2 coding for identifiers. 11866@end ifclear 11867 11868@item ^-h^/HELP^ 11869Causes @code{gnatchop} to generate a brief help summary to the standard 11870output file showing usage information. 11871 11872@item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^ 11873@cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop}) 11874Limit generated file names to the specified number @code{mm} 11875of characters. 11876This is useful if the 11877resulting set of files is required to be interoperable with systems 11878which limit the length of file names. 11879@ifset vms 11880If no value is given, or 11881if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given, 11882a default of 39, suitable for OpenVMS Alpha 11883Systems, is assumed 11884@end ifset 11885@ifclear vms 11886No space is allowed between the @option{-k} and the numeric value. The numeric 11887value may be omitted in which case a default of @option{-k8}, 11888suitable for use 11889with DOS-like file systems, is used. If no @option{-k} switch 11890is present then 11891there is no limit on the length of file names. 11892@end ifclear 11893 11894@item ^-p^/PRESERVE^ 11895@cindex @option{^-p^/PRESERVE^} (@code{gnatchop}) 11896Causes the file ^modification^creation^ time stamp of the input file to be 11897preserved and used for the time stamp of the output file(s). This may be 11898useful for preserving coherency of time stamps in an environment where 11899@code{gnatchop} is used as part of a standard build process. 11900 11901@item ^-q^/QUIET^ 11902@cindex @option{^-q^/QUIET^} (@code{gnatchop}) 11903Causes output of informational messages indicating the set of generated 11904files to be suppressed. Warnings and error messages are unaffected. 11905 11906@item ^-r^/REFERENCE^ 11907@cindex @option{^-r^/REFERENCE^} (@code{gnatchop}) 11908@findex Source_Reference 11909Generate @code{Source_Reference} pragmas. Use this switch if the output 11910files are regarded as temporary and development is to be done in terms 11911of the original unchopped file. This switch causes 11912@code{Source_Reference} pragmas to be inserted into each of the 11913generated files to refers back to the original file name and line number. 11914The result is that all error messages refer back to the original 11915unchopped file. 11916In addition, the debugging information placed into the object file (when 11917the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is 11918specified) 11919also refers back to this original file so that tools like profilers and 11920debuggers will give information in terms of the original unchopped file. 11921 11922If the original file to be chopped itself contains 11923a @code{Source_Reference} 11924pragma referencing a third file, then gnatchop respects 11925this pragma, and the generated @code{Source_Reference} pragmas 11926in the chopped file refer to the original file, with appropriate 11927line numbers. This is particularly useful when @code{gnatchop} 11928is used in conjunction with @code{gnatprep} to compile files that 11929contain preprocessing statements and multiple units. 11930 11931@item ^-v^/VERBOSE^ 11932@cindex @option{^-v^/VERBOSE^} (@code{gnatchop}) 11933Causes @code{gnatchop} to operate in verbose mode. The version 11934number and copyright notice are output, as well as exact copies of 11935the gnat1 commands spawned to obtain the chop control information. 11936 11937@item ^-w^/OVERWRITE^ 11938@cindex @option{^-w^/OVERWRITE^} (@code{gnatchop}) 11939Overwrite existing file names. Normally @code{gnatchop} regards it as a 11940fatal error if there is already a file with the same name as a 11941file it would otherwise output, in other words if the files to be 11942chopped contain duplicated units. This switch bypasses this 11943check, and causes all but the last instance of such duplicated 11944units to be skipped. 11945 11946@ifclear vms 11947@item --GCC=@var{xxxx} 11948@cindex @option{--GCC=} (@code{gnatchop}) 11949Specify the path of the GNAT parser to be used. When this switch is used, 11950no attempt is made to add the prefix to the GNAT parser executable. 11951@end ifclear 11952@end table 11953 11954@node Examples of gnatchop Usage 11955@section Examples of @code{gnatchop} Usage 11956 11957@table @code 11958@ifset vms 11959@item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES] 11960@end ifset 11961@ifclear vms 11962@item gnatchop -w hello_s.ada prerelease/files 11963@end ifclear 11964 11965Chops the source file @file{hello_s.ada}. The output files will be 11966placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^}, 11967overwriting any 11968files with matching names in that directory (no files in the current 11969directory are modified). 11970 11971@item gnatchop ^archive^ARCHIVE.^ 11972Chops the source file @file{^archive^ARCHIVE.^} 11973into the current directory. One 11974useful application of @code{gnatchop} is in sending sets of sources 11975around, for example in email messages. The required sources are simply 11976concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^ 11977command), and then 11978@command{gnatchop} is used at the other end to reconstitute the original 11979file names. 11980 11981@item gnatchop file1 file2 file3 direc 11982Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing 11983the resulting files in the directory @file{direc}. Note that if any units 11984occur more than once anywhere within this set of files, an error message 11985is generated, and no files are written. To override this check, use the 11986@option{^-w^/OVERWRITE^} switch, 11987in which case the last occurrence in the last file will 11988be the one that is output, and earlier duplicate occurrences for a given 11989unit will be skipped. 11990@end table 11991 11992@node Configuration Pragmas 11993@chapter Configuration Pragmas 11994@cindex Configuration pragmas 11995@cindex Pragmas, configuration 11996 11997@noindent 11998Configuration pragmas include those pragmas described as 11999such in the Ada Reference Manual, as well as 12000implementation-dependent pragmas that are configuration pragmas. 12001@xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}, 12002for details on these additional GNAT-specific configuration pragmas. 12003Most notably, the pragma @code{Source_File_Name}, which allows 12004specifying non-default names for source files, is a configuration 12005pragma. The following is a complete list of configuration pragmas 12006recognized by GNAT: 12007 12008@smallexample 12009 Ada_83 12010 Ada_95 12011 Ada_05 12012 Ada_2005 12013 Ada_12 12014 Ada_2012 12015 Annotate 12016 Assertion_Policy 12017 Assume_No_Invalid_Values 12018 C_Pass_By_Copy 12019 Check_Name 12020 Check_Policy 12021 Compile_Time_Error 12022 Compile_Time_Warning 12023 Compiler_Unit 12024 Component_Alignment 12025 Convention_Identifier 12026 Debug_Policy 12027 Detect_Blocking 12028 Default_Storage_Pool 12029 Discard_Names 12030 Elaboration_Checks 12031 Eliminate 12032 Extend_System 12033 Extensions_Allowed 12034 External_Name_Casing 12035 Fast_Math 12036 Favor_Top_Level 12037 Float_Representation 12038 Implicit_Packing 12039 Initialize_Scalars 12040 Interrupt_State 12041 License 12042 Locking_Policy 12043 Long_Float 12044 No_Run_Time 12045 No_Strict_Aliasing 12046 Normalize_Scalars 12047 Optimize_Alignment 12048 Persistent_BSS 12049 Polling 12050 Priority_Specific_Dispatching 12051 Profile 12052 Profile_Warnings 12053 Propagate_Exceptions 12054 Queuing_Policy 12055 Ravenscar 12056 Restricted_Run_Time 12057 Restrictions 12058 Restrictions_Warnings 12059 Reviewable 12060 Short_Circuit_And_Or 12061 Source_File_Name 12062 Source_File_Name_Project 12063 Style_Checks 12064 Suppress 12065 Suppress_Exception_Locations 12066 Task_Dispatching_Policy 12067 Universal_Data 12068 Unsuppress 12069 Use_VADS_Size 12070 Validity_Checks 12071 Warnings 12072 Wide_Character_Encoding 12073 12074@end smallexample 12075 12076@menu 12077* Handling of Configuration Pragmas:: 12078* The Configuration Pragmas Files:: 12079@end menu 12080 12081@node Handling of Configuration Pragmas 12082@section Handling of Configuration Pragmas 12083 12084Configuration pragmas may either appear at the start of a compilation 12085unit, or they can appear in a configuration pragma file to apply to 12086all compilations performed in a given compilation environment. 12087 12088GNAT also provides the @code{gnatchop} utility to provide an automatic 12089way to handle configuration pragmas following the semantics for 12090compilations (that is, files with multiple units), described in the RM. 12091See @ref{Operating gnatchop in Compilation Mode} for details. 12092However, for most purposes, it will be more convenient to edit the 12093@file{gnat.adc} file that contains configuration pragmas directly, 12094as described in the following section. 12095 12096In the case of @code{Restrictions} pragmas appearing as configuration 12097pragmas in individual compilation units, the exact handling depends on 12098the type of restriction. 12099 12100Restrictions that require partition-wide consistency (like 12101@code{No_Tasking}) are 12102recognized wherever they appear 12103and can be freely inherited, e.g. from a with'ed unit to the with'ing 12104unit. This makes sense since the binder will in any case insist on seeing 12105consistent use, so any unit not conforming to any restrictions that are 12106anywhere in the partition will be rejected, and you might as well find 12107that out at compile time rather than at bind time. 12108 12109For restrictions that do not require partition-wide consistency, e.g. 12110SPARK or No_Implementation_Attributes, in general the restriction applies 12111only to the unit in which the pragma appears, and not to any other units. 12112 12113The exception is No_Elaboration_Code which always applies to the entire 12114object file from a compilation, i.e. to the body, spec, and all subunits. 12115This restriction can be specified in a configuration pragma file, or it 12116can be on the body and/or the spec (in eithe case it applies to all the 12117relevant units). It can appear on a subunit only if it has previously 12118appeared in the body of spec. 12119 12120@node The Configuration Pragmas Files 12121@section The Configuration Pragmas Files 12122@cindex @file{gnat.adc} 12123 12124@noindent 12125In GNAT a compilation environment is defined by the current 12126directory at the time that a compile command is given. This current 12127directory is searched for a file whose name is @file{gnat.adc}. If 12128this file is present, it is expected to contain one or more 12129configuration pragmas that will be applied to the current compilation. 12130However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not 12131considered. 12132 12133Configuration pragmas may be entered into the @file{gnat.adc} file 12134either by running @code{gnatchop} on a source file that consists only of 12135configuration pragmas, or more conveniently by 12136direct editing of the @file{gnat.adc} file, which is a standard format 12137source file. 12138 12139In addition to @file{gnat.adc}, additional files containing configuration 12140pragmas may be applied to the current compilation using the switch 12141@option{-gnatec}@var{path}. @var{path} must designate an existing file that 12142contains only configuration pragmas. These configuration pragmas are 12143in addition to those found in @file{gnat.adc} (provided @file{gnat.adc} 12144is present and switch @option{-gnatA} is not used). 12145 12146It is allowed to specify several switches @option{-gnatec}, all of which 12147will be taken into account. 12148 12149If you are using project file, a separate mechanism is provided using 12150project attributes, see @ref{Specifying Configuration Pragmas} for more 12151details. 12152 12153@ifset vms 12154Of special interest to GNAT OpenVMS Alpha is the following 12155configuration pragma: 12156 12157@smallexample @c ada 12158@cartouche 12159pragma Extend_System (Aux_DEC); 12160@end cartouche 12161@end smallexample 12162 12163@noindent 12164In the presence of this pragma, GNAT adds to the definition of the 12165predefined package SYSTEM all the additional types and subprograms that are 12166defined in HP Ada. See @ref{Compatibility with HP Ada} for details. 12167@end ifset 12168 12169@node Handling Arbitrary File Naming Conventions Using gnatname 12170@chapter Handling Arbitrary File Naming Conventions Using @code{gnatname} 12171@cindex Arbitrary File Naming Conventions 12172 12173@menu 12174* Arbitrary File Naming Conventions:: 12175* Running gnatname:: 12176* Switches for gnatname:: 12177* Examples of gnatname Usage:: 12178@end menu 12179 12180@node Arbitrary File Naming Conventions 12181@section Arbitrary File Naming Conventions 12182 12183@noindent 12184The GNAT compiler must be able to know the source file name of a compilation 12185unit. When using the standard GNAT default file naming conventions 12186(@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler 12187does not need additional information. 12188 12189@noindent 12190When the source file names do not follow the standard GNAT default file naming 12191conventions, the GNAT compiler must be given additional information through 12192a configuration pragmas file (@pxref{Configuration Pragmas}) 12193or a project file. 12194When the non-standard file naming conventions are well-defined, 12195a small number of pragmas @code{Source_File_Name} specifying a naming pattern 12196(@pxref{Alternative File Naming Schemes}) may be sufficient. However, 12197if the file naming conventions are irregular or arbitrary, a number 12198of pragma @code{Source_File_Name} for individual compilation units 12199must be defined. 12200To help maintain the correspondence between compilation unit names and 12201source file names within the compiler, 12202GNAT provides a tool @code{gnatname} to generate the required pragmas for a 12203set of files. 12204 12205@node Running gnatname 12206@section Running @code{gnatname} 12207 12208@noindent 12209The usual form of the @code{gnatname} command is 12210 12211@smallexample 12212@c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns} 12213@c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]} 12214@c Expanding @ovar macro inline (explanation in macro def comments) 12215$ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]} 12216 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]} 12217@end smallexample 12218 12219@noindent 12220All of the arguments are optional. If invoked without any argument, 12221@code{gnatname} will display its usage. 12222 12223@noindent 12224When used with at least one naming pattern, @code{gnatname} will attempt to 12225find all the compilation units in files that follow at least one of the 12226naming patterns. To find these compilation units, 12227@code{gnatname} will use the GNAT compiler in syntax-check-only mode on all 12228regular files. 12229 12230@noindent 12231One or several Naming Patterns may be given as arguments to @code{gnatname}. 12232Each Naming Pattern is enclosed between double quotes (or single 12233quotes on Windows). 12234A Naming Pattern is a regular expression similar to the wildcard patterns 12235used in file names by the Unix shells or the DOS prompt. 12236 12237@noindent 12238@code{gnatname} may be called with several sections of directories/patterns. 12239Sections are separated by switch @code{--and}. In each section, there must be 12240at least one pattern. If no directory is specified in a section, the current 12241directory (or the project directory is @code{-P} is used) is implied. 12242The options other that the directory switches and the patterns apply globally 12243even if they are in different sections. 12244 12245@noindent 12246Examples of Naming Patterns are 12247 12248@smallexample 12249 "*.[12].ada" 12250 "*.ad[sb]*" 12251 "body_*" "spec_*" 12252@end smallexample 12253 12254@noindent 12255For a more complete description of the syntax of Naming Patterns, 12256see the second kind of regular expressions described in @file{g-regexp.ads} 12257(the ``Glob'' regular expressions). 12258 12259@noindent 12260When invoked with no switch @code{-P}, @code{gnatname} will create a 12261configuration pragmas file @file{gnat.adc} in the current working directory, 12262with pragmas @code{Source_File_Name} for each file that contains a valid Ada 12263unit. 12264 12265@node Switches for gnatname 12266@section Switches for @code{gnatname} 12267 12268@noindent 12269Switches for @code{gnatname} must precede any specified Naming Pattern. 12270 12271@noindent 12272You may specify any of the following switches to @code{gnatname}: 12273 12274@table @option 12275@c !sort! 12276 12277@item --version 12278@cindex @option{--version} @command{gnatname} 12279Display Copyright and version, then exit disregarding all other options. 12280 12281@item --help 12282@cindex @option{--help} @command{gnatname} 12283If @option{--version} was not used, display usage, then exit disregarding 12284all other options. 12285 12286@item --and 12287Start another section of directories/patterns. 12288 12289@item ^-c^/CONFIG_FILE=^@file{file} 12290@cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname}) 12291Create a configuration pragmas file @file{file} (instead of the default 12292@file{gnat.adc}). 12293@ifclear vms 12294There may be zero, one or more space between @option{-c} and 12295@file{file}. 12296@end ifclear 12297@file{file} may include directory information. @file{file} must be 12298writable. There may be only one switch @option{^-c^/CONFIG_FILE^}. 12299When a switch @option{^-c^/CONFIG_FILE^} is 12300specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below). 12301 12302@item ^-d^/SOURCE_DIRS=^@file{dir} 12303@cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname}) 12304Look for source files in directory @file{dir}. There may be zero, one or more 12305spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}. 12306When a switch @option{^-d^/SOURCE_DIRS^} 12307is specified, the current working directory will not be searched for source 12308files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^} 12309or @option{^-D^/DIR_FILES^} switch. 12310Several switches @option{^-d^/SOURCE_DIRS^} may be specified. 12311If @file{dir} is a relative path, it is relative to the directory of 12312the configuration pragmas file specified with switch 12313@option{^-c^/CONFIG_FILE^}, 12314or to the directory of the project file specified with switch 12315@option{^-P^/PROJECT_FILE^} or, 12316if neither switch @option{^-c^/CONFIG_FILE^} 12317nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the 12318current working directory. The directory 12319specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable. 12320 12321@item ^-D^/DIRS_FILE=^@file{file} 12322@cindex @option{^-D^/DIRS_FILE^} (@code{gnatname}) 12323Look for source files in all directories listed in text file @file{file}. 12324There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^} 12325and @file{file}. 12326@file{file} must be an existing, readable text file. 12327Each nonempty line in @file{file} must be a directory. 12328Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many 12329switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in 12330@file{file}. 12331 12332@item ^-f^/FOREIGN_PATTERN=^@file{pattern} 12333@cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname}) 12334Foreign patterns. Using this switch, it is possible to add sources of languages 12335other than Ada to the list of sources of a project file. 12336It is only useful if a ^-P^/PROJECT_FILE^ switch is used. 12337For example, 12338@smallexample 12339gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada" 12340@end smallexample 12341@noindent 12342will look for Ada units in all files with the @file{.ada} extension, 12343and will add to the list of file for project @file{prj.gpr} the C files 12344with extension @file{.^c^C^}. 12345 12346@item ^-h^/HELP^ 12347@cindex @option{^-h^/HELP^} (@code{gnatname}) 12348Output usage (help) information. The output is written to @file{stdout}. 12349 12350@item ^-P^/PROJECT_FILE=^@file{proj} 12351@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname}) 12352Create or update project file @file{proj}. There may be zero, one or more space 12353between @option{-P} and @file{proj}. @file{proj} may include directory 12354information. @file{proj} must be writable. 12355There may be only one switch @option{^-P^/PROJECT_FILE^}. 12356When a switch @option{^-P^/PROJECT_FILE^} is specified, 12357no switch @option{^-c^/CONFIG_FILE^} may be specified. 12358 12359@item ^-v^/VERBOSE^ 12360@cindex @option{^-v^/VERBOSE^} (@code{gnatname}) 12361Verbose mode. Output detailed explanation of behavior to @file{stdout}. 12362This includes name of the file written, the name of the directories to search 12363and, for each file in those directories whose name matches at least one of 12364the Naming Patterns, an indication of whether the file contains a unit, 12365and if so the name of the unit. 12366 12367@item ^-v -v^/VERBOSE /VERBOSE^ 12368@cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname}) 12369Very Verbose mode. In addition to the output produced in verbose mode, 12370for each file in the searched directories whose name matches none of 12371the Naming Patterns, an indication is given that there is no match. 12372 12373@item ^-x^/EXCLUDED_PATTERN=^@file{pattern} 12374@cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname}) 12375Excluded patterns. Using this switch, it is possible to exclude some files 12376that would match the name patterns. For example, 12377@smallexample 12378gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada" 12379@end smallexample 12380@noindent 12381will look for Ada units in all files with the @file{.ada} extension, 12382except those whose names end with @file{_nt.ada}. 12383 12384@end table 12385 12386@node Examples of gnatname Usage 12387@section Examples of @code{gnatname} Usage 12388 12389@ifset vms 12390@smallexample 12391$ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*" 12392@end smallexample 12393@end ifset 12394 12395@ifclear vms 12396@smallexample 12397$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" 12398@end smallexample 12399@end ifclear 12400 12401@noindent 12402In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist 12403and be writable. In addition, the directory 12404@file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by 12405@option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable. 12406 12407@ifclear vms 12408Note the optional spaces after @option{-c} and @option{-d}. 12409@end ifclear 12410 12411@smallexample 12412@ifclear vms 12413$ gnatname -P/home/me/proj -x "*_nt_body.ada" 12414 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" 12415@end ifclear 12416@ifset vms 12417$ gnatname /PROJECT_FILE=[HOME.ME]PROJ 12418 /EXCLUDED_PATTERN=*_nt_body.ada 12419 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS]) 12420 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*" 12421@end ifset 12422@end smallexample 12423 12424Note that several switches @option{^-d^/SOURCE_DIRS^} may be used, 12425even in conjunction with one or several switches 12426@option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern 12427are used in this example. 12428 12429@c ***************************************** 12430@c * G N A T P r o j e c t M a n a g e r * 12431@c ***************************************** 12432 12433@c ------ macros for projects.texi 12434@c These macros are needed when building the gprbuild documentation, but 12435@c should have no effect in the gnat user's guide 12436 12437@macro CODESAMPLE{TXT} 12438@smallexample 12439@group 12440\TXT\ 12441@end group 12442@end smallexample 12443@end macro 12444 12445@macro PROJECTFILE{TXT} 12446@CODESAMPLE{\TXT\} 12447@end macro 12448 12449@c simulates a newline when in a @CODESAMPLE 12450@macro NL{} 12451@end macro 12452 12453@macro TIP{TXT} 12454@quotation 12455@noindent 12456\TXT\ 12457@end quotation 12458@end macro 12459 12460@macro TIPHTML{TXT} 12461\TXT\ 12462@end macro 12463 12464@macro IMPORTANT{TXT} 12465@quotation 12466@noindent 12467\TXT\ 12468@end quotation 12469 12470@end macro 12471 12472@macro NOTE{TXT} 12473@quotation 12474@noindent 12475\TXT\ 12476@end quotation 12477@end macro 12478 12479@include projects.texi 12480 12481@c ***************************************** 12482@c * Cross-referencing tools 12483@c ***************************************** 12484 12485@node The Cross-Referencing Tools gnatxref and gnatfind 12486@chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind} 12487@findex gnatxref 12488@findex gnatfind 12489 12490@noindent 12491The compiler generates cross-referencing information (unless 12492you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files. 12493This information indicates where in the source each entity is declared and 12494referenced. Note that entities in package Standard are not included, but 12495entities in all other predefined units are included in the output. 12496 12497Before using any of these two tools, you need to compile successfully your 12498application, so that GNAT gets a chance to generate the cross-referencing 12499information. 12500 12501The two tools @code{gnatxref} and @code{gnatfind} take advantage of this 12502information to provide the user with the capability to easily locate the 12503declaration and references to an entity. These tools are quite similar, 12504the difference being that @code{gnatfind} is intended for locating 12505definitions and/or references to a specified entity or entities, whereas 12506@code{gnatxref} is oriented to generating a full report of all 12507cross-references. 12508 12509To use these tools, you must not compile your application using the 12510@option{-gnatx} switch on the @command{gnatmake} command line 12511(@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing 12512information will not be generated. 12513 12514Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file, 12515use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}). 12516 12517@menu 12518* Switches for gnatxref:: 12519* Switches for gnatfind:: 12520* Project Files for gnatxref and gnatfind:: 12521* Regular Expressions in gnatfind and gnatxref:: 12522* Examples of gnatxref Usage:: 12523* Examples of gnatfind Usage:: 12524@end menu 12525 12526@node Switches for gnatxref 12527@section @code{gnatxref} Switches 12528 12529@noindent 12530The command invocation for @code{gnatxref} is: 12531@smallexample 12532@c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]} 12533@c Expanding @ovar macro inline (explanation in macro def comments) 12534$ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]} 12535@end smallexample 12536 12537@noindent 12538where 12539 12540@table @var 12541@item sourcefile1 12542@itemx sourcefile2 12543identifies the source files for which a report is to be generated. The 12544``with''ed units will be processed too. You must provide at least one file. 12545 12546These file names are considered to be regular expressions, so for instance 12547specifying @file{source*.adb} is the same as giving every file in the current 12548directory whose name starts with @file{source} and whose extension is 12549@file{adb}. 12550 12551You shouldn't specify any directory name, just base names. @command{gnatxref} 12552and @command{gnatfind} will be able to locate these files by themselves using 12553the source path. If you specify directories, no result is produced. 12554 12555@end table 12556 12557@noindent 12558The switches can be: 12559@table @option 12560@c !sort! 12561@item --version 12562@cindex @option{--version} @command{gnatxref} 12563Display Copyright and version, then exit disregarding all other options. 12564 12565@item --help 12566@cindex @option{--help} @command{gnatxref} 12567If @option{--version} was not used, display usage, then exit disregarding 12568all other options. 12569 12570@item ^-a^/ALL_FILES^ 12571@cindex @option{^-a^/ALL_FILES^} (@command{gnatxref}) 12572If this switch is present, @code{gnatfind} and @code{gnatxref} will parse 12573the read-only files found in the library search path. Otherwise, these files 12574will be ignored. This option can be used to protect Gnat sources or your own 12575libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} 12576much faster, and their output much smaller. Read-only here refers to access 12577or permissions status in the file system for the current user. 12578 12579@item -aIDIR 12580@cindex @option{-aIDIR} (@command{gnatxref}) 12581When looking for source files also look in directory DIR. The order in which 12582source file search is undertaken is the same as for @command{gnatmake}. 12583 12584@item -aODIR 12585@cindex @option{-aODIR} (@command{gnatxref}) 12586When searching for library and object files, look in directory 12587DIR. The order in which library files are searched is the same as for 12588@command{gnatmake}. 12589 12590@item -nostdinc 12591@cindex @option{-nostdinc} (@command{gnatxref}) 12592Do not look for sources in the system default directory. 12593 12594@item -nostdlib 12595@cindex @option{-nostdlib} (@command{gnatxref}) 12596Do not look for library files in the system default directory. 12597 12598@item --ext=@var{extension} 12599@cindex @option{--ext} (@command{gnatxref}) 12600Specify an alternate ali file extension. The default is @code{ali} and other 12601extensions (e.g. @code{sli} for SPARK library files) may be specified via this 12602switch. Note that if this switch overrides the default, which means that only 12603the new extension will be considered. 12604 12605@item --RTS=@var{rts-path} 12606@cindex @option{--RTS} (@command{gnatxref}) 12607Specifies the default location of the runtime library. Same meaning as the 12608equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}). 12609 12610@item ^-d^/DERIVED_TYPES^ 12611@cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref}) 12612If this switch is set @code{gnatxref} will output the parent type 12613reference for each matching derived types. 12614 12615@item ^-f^/FULL_PATHNAME^ 12616@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref}) 12617If this switch is set, the output file names will be preceded by their 12618directory (if the file was found in the search path). If this switch is 12619not set, the directory will not be printed. 12620 12621@item ^-g^/IGNORE_LOCALS^ 12622@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref}) 12623If this switch is set, information is output only for library-level 12624entities, ignoring local entities. The use of this switch may accelerate 12625@code{gnatfind} and @code{gnatxref}. 12626 12627@item -IDIR 12628@cindex @option{-IDIR} (@command{gnatxref}) 12629Equivalent to @samp{-aODIR -aIDIR}. 12630 12631@item -pFILE 12632@cindex @option{-pFILE} (@command{gnatxref}) 12633Specify a project file to use @xref{GNAT Project Manager}. 12634If you need to use the @file{.gpr} 12635project files, you should use gnatxref through the GNAT driver 12636(@command{gnat xref -Pproject}). 12637 12638By default, @code{gnatxref} and @code{gnatfind} will try to locate a 12639project file in the current directory. 12640 12641If a project file is either specified or found by the tools, then the content 12642of the source directory and object directory lines are added as if they 12643had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} 12644and @samp{^-aO^OBJECT_SEARCH^}. 12645@item ^-u^/UNUSED^ 12646Output only unused symbols. This may be really useful if you give your 12647main compilation unit on the command line, as @code{gnatxref} will then 12648display every unused entity and 'with'ed package. 12649 12650@ifclear vms 12651@item -v 12652Instead of producing the default output, @code{gnatxref} will generate a 12653@file{tags} file that can be used by vi. For examples how to use this 12654feature, see @ref{Examples of gnatxref Usage}. The tags file is output 12655to the standard output, thus you will have to redirect it to a file. 12656@end ifclear 12657 12658@end table 12659 12660@noindent 12661All these switches may be in any order on the command line, and may even 12662appear after the file names. They need not be separated by spaces, thus 12663you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of 12664@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. 12665 12666@node Switches for gnatfind 12667@section @code{gnatfind} Switches 12668 12669@noindent 12670The command line for @code{gnatfind} is: 12671 12672@smallexample 12673@c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]} 12674@c @r{[}@var{file1} @var{file2} @dots{}] 12675@c Expanding @ovar macro inline (explanation in macro def comments) 12676$ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]} 12677 @r{[}@var{file1} @var{file2} @dots{}@r{]} 12678@end smallexample 12679 12680@noindent 12681where 12682 12683@table @var 12684@item pattern 12685An entity will be output only if it matches the regular expression found 12686in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}. 12687 12688Omitting the pattern is equivalent to specifying @samp{*}, which 12689will match any entity. Note that if you do not provide a pattern, you 12690have to provide both a sourcefile and a line. 12691 12692Entity names are given in Latin-1, with uppercase/lowercase equivalence 12693for matching purposes. At the current time there is no support for 126948-bit codes other than Latin-1, or for wide characters in identifiers. 12695 12696@item sourcefile 12697@code{gnatfind} will look for references, bodies or declarations 12698of symbols referenced in @file{@var{sourcefile}}, at line @var{line} 12699and column @var{column}. See @ref{Examples of gnatfind Usage} 12700for syntax examples. 12701 12702@item line 12703is a decimal integer identifying the line number containing 12704the reference to the entity (or entities) to be located. 12705 12706@item column 12707is a decimal integer identifying the exact location on the 12708line of the first character of the identifier for the 12709entity reference. Columns are numbered from 1. 12710 12711@item file1 file2 @dots{} 12712The search will be restricted to these source files. If none are given, then 12713the search will be done for every library file in the search path. 12714These file must appear only after the pattern or sourcefile. 12715 12716These file names are considered to be regular expressions, so for instance 12717specifying @file{source*.adb} is the same as giving every file in the current 12718directory whose name starts with @file{source} and whose extension is 12719@file{adb}. 12720 12721The location of the spec of the entity will always be displayed, even if it 12722isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The 12723occurrences of the entity in the separate units of the ones given on the 12724command line will also be displayed. 12725 12726Note that if you specify at least one file in this part, @code{gnatfind} may 12727sometimes not be able to find the body of the subprograms. 12728 12729@end table 12730 12731@noindent 12732At least one of 'sourcefile' or 'pattern' has to be present on 12733the command line. 12734 12735The following switches are available: 12736@table @option 12737@c !sort! 12738 12739@cindex @option{--version} @command{gnatfind} 12740Display Copyright and version, then exit disregarding all other options. 12741 12742@item --help 12743@cindex @option{--help} @command{gnatfind} 12744If @option{--version} was not used, display usage, then exit disregarding 12745all other options. 12746 12747@item ^-a^/ALL_FILES^ 12748@cindex @option{^-a^/ALL_FILES^} (@command{gnatfind}) 12749If this switch is present, @code{gnatfind} and @code{gnatxref} will parse 12750the read-only files found in the library search path. Otherwise, these files 12751will be ignored. This option can be used to protect Gnat sources or your own 12752libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref} 12753much faster, and their output much smaller. Read-only here refers to access 12754or permission status in the file system for the current user. 12755 12756@item -aIDIR 12757@cindex @option{-aIDIR} (@command{gnatfind}) 12758When looking for source files also look in directory DIR. The order in which 12759source file search is undertaken is the same as for @command{gnatmake}. 12760 12761@item -aODIR 12762@cindex @option{-aODIR} (@command{gnatfind}) 12763When searching for library and object files, look in directory 12764DIR. The order in which library files are searched is the same as for 12765@command{gnatmake}. 12766 12767@item -nostdinc 12768@cindex @option{-nostdinc} (@command{gnatfind}) 12769Do not look for sources in the system default directory. 12770 12771@item -nostdlib 12772@cindex @option{-nostdlib} (@command{gnatfind}) 12773Do not look for library files in the system default directory. 12774 12775@item --ext=@var{extension} 12776@cindex @option{--ext} (@command{gnatfind}) 12777Specify an alternate ali file extension. The default is @code{ali} and other 12778extensions (e.g. @code{sli} for SPARK library files) may be specified via this 12779switch. Note that if this switch overrides the default, which means that only 12780the new extension will be considered. 12781 12782@item --RTS=@var{rts-path} 12783@cindex @option{--RTS} (@command{gnatfind}) 12784Specifies the default location of the runtime library. Same meaning as the 12785equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}). 12786 12787@item ^-d^/DERIVED_TYPE_INFORMATION^ 12788@cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind}) 12789If this switch is set, then @code{gnatfind} will output the parent type 12790reference for each matching derived types. 12791 12792@item ^-e^/EXPRESSIONS^ 12793@cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind}) 12794By default, @code{gnatfind} accept the simple regular expression set for 12795@samp{pattern}. If this switch is set, then the pattern will be 12796considered as full Unix-style regular expression. 12797 12798@item ^-f^/FULL_PATHNAME^ 12799@cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind}) 12800If this switch is set, the output file names will be preceded by their 12801directory (if the file was found in the search path). If this switch is 12802not set, the directory will not be printed. 12803 12804@item ^-g^/IGNORE_LOCALS^ 12805@cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind}) 12806If this switch is set, information is output only for library-level 12807entities, ignoring local entities. The use of this switch may accelerate 12808@code{gnatfind} and @code{gnatxref}. 12809 12810@item -IDIR 12811@cindex @option{-IDIR} (@command{gnatfind}) 12812Equivalent to @samp{-aODIR -aIDIR}. 12813 12814@item -pFILE 12815@cindex @option{-pFILE} (@command{gnatfind}) 12816Specify a project file (@pxref{GNAT Project Manager}) to use. 12817By default, @code{gnatxref} and @code{gnatfind} will try to locate a 12818project file in the current directory. 12819 12820If a project file is either specified or found by the tools, then the content 12821of the source directory and object directory lines are added as if they 12822had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and 12823@samp{^-aO^/OBJECT_SEARCH^}. 12824 12825@item ^-r^/REFERENCES^ 12826@cindex @option{^-r^/REFERENCES^} (@command{gnatfind}) 12827By default, @code{gnatfind} will output only the information about the 12828declaration, body or type completion of the entities. If this switch is 12829set, the @code{gnatfind} will locate every reference to the entities in 12830the files specified on the command line (or in every file in the search 12831path if no file is given on the command line). 12832 12833@item ^-s^/PRINT_LINES^ 12834@cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind}) 12835If this switch is set, then @code{gnatfind} will output the content 12836of the Ada source file lines were the entity was found. 12837 12838@item ^-t^/TYPE_HIERARCHY^ 12839@cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind}) 12840If this switch is set, then @code{gnatfind} will output the type hierarchy for 12841the specified type. It act like -d option but recursively from parent 12842type to parent type. When this switch is set it is not possible to 12843specify more than one file. 12844 12845@end table 12846 12847@noindent 12848All these switches may be in any order on the command line, and may even 12849appear after the file names. They need not be separated by spaces, thus 12850you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of 12851@samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}. 12852 12853As stated previously, gnatfind will search in every directory in the 12854search path. You can force it to look only in the current directory if 12855you specify @code{*} at the end of the command line. 12856 12857@node Project Files for gnatxref and gnatfind 12858@section Project Files for @command{gnatxref} and @command{gnatfind} 12859 12860@noindent 12861Project files allow a programmer to specify how to compile its 12862application, where to find sources, etc. These files are used 12863@ifclear vms 12864primarily by GPS, but they can also be used 12865@end ifclear 12866by the two tools 12867@code{gnatxref} and @code{gnatfind}. 12868 12869A project file name must end with @file{.gpr}. If a single one is 12870present in the current directory, then @code{gnatxref} and @code{gnatfind} will 12871extract the information from it. If multiple project files are found, none of 12872them is read, and you have to use the @samp{-p} switch to specify the one 12873you want to use. 12874 12875The following lines can be included, even though most of them have default 12876values which can be used in most cases. 12877The lines can be entered in any order in the file. 12878Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of 12879each line. If you have multiple instances, only the last one is taken into 12880account. 12881 12882@table @code 12883@item src_dir=DIR 12884[default: @code{"^./^[]^"}] 12885specifies a directory where to look for source files. Multiple @code{src_dir} 12886lines can be specified and they will be searched in the order they 12887are specified. 12888 12889@item obj_dir=DIR 12890[default: @code{"^./^[]^"}] 12891specifies a directory where to look for object and library files. Multiple 12892@code{obj_dir} lines can be specified, and they will be searched in the order 12893they are specified 12894 12895@item comp_opt=SWITCHES 12896[default: @code{""}] 12897creates a variable which can be referred to subsequently by using 12898the @code{$@{comp_opt@}} notation. This is intended to store the default 12899switches given to @command{gnatmake} and @command{gcc}. 12900 12901@item bind_opt=SWITCHES 12902[default: @code{""}] 12903creates a variable which can be referred to subsequently by using 12904the @samp{$@{bind_opt@}} notation. This is intended to store the default 12905switches given to @command{gnatbind}. 12906 12907@item link_opt=SWITCHES 12908[default: @code{""}] 12909creates a variable which can be referred to subsequently by using 12910the @samp{$@{link_opt@}} notation. This is intended to store the default 12911switches given to @command{gnatlink}. 12912 12913@item main=EXECUTABLE 12914[default: @code{""}] 12915specifies the name of the executable for the application. This variable can 12916be referred to in the following lines by using the @samp{$@{main@}} notation. 12917 12918@ifset vms 12919@item comp_cmd=COMMAND 12920[default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}] 12921@end ifset 12922@ifclear vms 12923@item comp_cmd=COMMAND 12924[default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}] 12925@end ifclear 12926specifies the command used to compile a single file in the application. 12927 12928@ifset vms 12929@item make_cmd=COMMAND 12930[default: @code{"GNAT MAKE $@{main@} 12931/SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} 12932/DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} 12933/BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}] 12934@end ifset 12935@ifclear vms 12936@item make_cmd=COMMAND 12937[default: @code{"gnatmake $@{main@} -aI$@{src_dir@} 12938-aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} 12939-bargs $@{bind_opt@} -largs $@{link_opt@}"}] 12940@end ifclear 12941specifies the command used to recompile the whole application. 12942 12943@item run_cmd=COMMAND 12944[default: @code{"$@{main@}"}] 12945specifies the command used to run the application. 12946 12947@item debug_cmd=COMMAND 12948[default: @code{"gdb $@{main@}"}] 12949specifies the command used to debug the application 12950 12951@end table 12952 12953@noindent 12954@command{gnatxref} and @command{gnatfind} only take into account the 12955@code{src_dir} and @code{obj_dir} lines, and ignore the others. 12956 12957@node Regular Expressions in gnatfind and gnatxref 12958@section Regular Expressions in @code{gnatfind} and @code{gnatxref} 12959 12960@noindent 12961As specified in the section about @command{gnatfind}, the pattern can be a 12962regular expression. Actually, there are to set of regular expressions 12963which are recognized by the program: 12964 12965@table @code 12966@item globbing patterns 12967These are the most usual regular expression. They are the same that you 12968generally used in a Unix shell command line, or in a DOS session. 12969 12970Here is a more formal grammar: 12971@smallexample 12972@group 12973@iftex 12974@leftskip=.5cm 12975@end iftex 12976regexp ::= term 12977term ::= elmt -- matches elmt 12978term ::= elmt elmt -- concatenation (elmt then elmt) 12979term ::= * -- any string of 0 or more characters 12980term ::= ? -- matches any character 12981term ::= [char @{char@}] -- matches any character listed 12982term ::= [char - char] -- matches any character in range 12983@end group 12984@end smallexample 12985 12986@item full regular expression 12987The second set of regular expressions is much more powerful. This is the 12988type of regular expressions recognized by utilities such a @file{grep}. 12989 12990The following is the form of a regular expression, expressed in Ada 12991reference manual style BNF is as follows 12992 12993@smallexample 12994@iftex 12995@leftskip=.5cm 12996@end iftex 12997@group 12998regexp ::= term @{| term@} -- alternation (term or term @dots{}) 12999 13000term ::= item @{item@} -- concatenation (item then item) 13001 13002item ::= elmt -- match elmt 13003item ::= elmt * -- zero or more elmt's 13004item ::= elmt + -- one or more elmt's 13005item ::= elmt ? -- matches elmt or nothing 13006@end group 13007@group 13008elmt ::= nschar -- matches given character 13009elmt ::= [nschar @{nschar@}] -- matches any character listed 13010elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed 13011elmt ::= [char - char] -- matches chars in given range 13012elmt ::= \ char -- matches given character 13013elmt ::= . -- matches any single character 13014elmt ::= ( regexp ) -- parens used for grouping 13015 13016char ::= any character, including special characters 13017nschar ::= any character except ()[].*+?^^^ 13018@end group 13019@end smallexample 13020 13021Following are a few examples: 13022 13023@table @samp 13024@item abcde|fghi 13025will match any of the two strings @samp{abcde} and @samp{fghi}, 13026 13027@item abc*d 13028will match any string like @samp{abd}, @samp{abcd}, @samp{abccd}, 13029@samp{abcccd}, and so on, 13030 13031@item [a-z]+ 13032will match any string which has only lowercase characters in it (and at 13033least one character. 13034 13035@end table 13036@end table 13037 13038@node Examples of gnatxref Usage 13039@section Examples of @code{gnatxref} Usage 13040 13041@subsection General Usage 13042 13043@noindent 13044For the following examples, we will consider the following units: 13045 13046@smallexample @c ada 13047@group 13048@cartouche 13049main.ads: 130501: with Bar; 130512: package Main is 130523: procedure Foo (B : in Integer); 130534: C : Integer; 130545: private 130556: D : Integer; 130567: end Main; 13057 13058main.adb: 130591: package body Main is 130602: procedure Foo (B : in Integer) is 130613: begin 130624: C := B; 130635: D := B; 130646: Bar.Print (B); 130657: Bar.Print (C); 130668: end Foo; 130679: end Main; 13068 13069bar.ads: 130701: package Bar is 130712: procedure Print (B : Integer); 130723: end bar; 13073@end cartouche 13074@end group 13075@end smallexample 13076 13077@table @code 13078 13079@noindent 13080The first thing to do is to recompile your application (for instance, in 13081that case just by doing a @samp{gnatmake main}, so that GNAT generates 13082the cross-referencing information. 13083You can then issue any of the following commands: 13084 13085@item gnatxref main.adb 13086@code{gnatxref} generates cross-reference information for main.adb 13087and every unit 'with'ed by main.adb. 13088 13089The output would be: 13090@smallexample 13091@iftex 13092@leftskip=0cm 13093@end iftex 13094B Type: Integer 13095 Decl: bar.ads 2:22 13096B Type: Integer 13097 Decl: main.ads 3:20 13098 Body: main.adb 2:20 13099 Ref: main.adb 4:13 5:13 6:19 13100Bar Type: Unit 13101 Decl: bar.ads 1:9 13102 Ref: main.adb 6:8 7:8 13103 main.ads 1:6 13104C Type: Integer 13105 Decl: main.ads 4:5 13106 Modi: main.adb 4:8 13107 Ref: main.adb 7:19 13108D Type: Integer 13109 Decl: main.ads 6:5 13110 Modi: main.adb 5:8 13111Foo Type: Unit 13112 Decl: main.ads 3:15 13113 Body: main.adb 2:15 13114Main Type: Unit 13115 Decl: main.ads 2:9 13116 Body: main.adb 1:14 13117Print Type: Unit 13118 Decl: bar.ads 2:15 13119 Ref: main.adb 6:12 7:12 13120@end smallexample 13121 13122@noindent 13123that is the entity @code{Main} is declared in main.ads, line 2, column 9, 13124its body is in main.adb, line 1, column 14 and is not referenced any where. 13125 13126The entity @code{Print} is declared in bar.ads, line 2, column 15 and it 13127is referenced in main.adb, line 6 column 12 and line 7 column 12. 13128 13129@item gnatxref package1.adb package2.ads 13130@code{gnatxref} will generates cross-reference information for 13131package1.adb, package2.ads and any other package 'with'ed by any 13132of these. 13133 13134@end table 13135 13136@ifclear vms 13137@subsection Using gnatxref with vi 13138 13139@code{gnatxref} can generate a tags file output, which can be used 13140directly from @command{vi}. Note that the standard version of @command{vi} 13141will not work properly with overloaded symbols. Consider using another 13142free implementation of @command{vi}, such as @command{vim}. 13143 13144@smallexample 13145$ gnatxref -v gnatfind.adb > tags 13146@end smallexample 13147 13148@noindent 13149will generate the tags file for @code{gnatfind} itself (if the sources 13150are in the search path!). 13151 13152From @command{vi}, you can then use the command @samp{:tag @var{entity}} 13153(replacing @var{entity} by whatever you are looking for), and vi will 13154display a new file with the corresponding declaration of entity. 13155@end ifclear 13156 13157@node Examples of gnatfind Usage 13158@section Examples of @code{gnatfind} Usage 13159 13160@table @code 13161 13162@item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb 13163Find declarations for all entities xyz referenced at least once in 13164main.adb. The references are search in every library file in the search 13165path. 13166 13167The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^} 13168switch is set) 13169 13170The output will look like: 13171@smallexample 13172^directory/^[directory]^main.ads:106:14: xyz <= declaration 13173^directory/^[directory]^main.adb:24:10: xyz <= body 13174^directory/^[directory]^foo.ads:45:23: xyz <= declaration 13175@end smallexample 13176 13177@noindent 13178that is to say, one of the entities xyz found in main.adb is declared at 13179line 12 of main.ads (and its body is in main.adb), and another one is 13180declared at line 45 of foo.ads 13181 13182@item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb 13183This is the same command as the previous one, instead @code{gnatfind} will 13184display the content of the Ada source file lines. 13185 13186The output will look like: 13187 13188@smallexample 13189^directory/^[directory]^main.ads:106:14: xyz <= declaration 13190 procedure xyz; 13191^directory/^[directory]^main.adb:24:10: xyz <= body 13192 procedure xyz is 13193^directory/^[directory]^foo.ads:45:23: xyz <= declaration 13194 xyz : Integer; 13195@end smallexample 13196 13197@noindent 13198This can make it easier to find exactly the location your are looking 13199for. 13200 13201@item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb 13202Find references to all entities containing an x that are 13203referenced on line 123 of main.ads. 13204The references will be searched only in main.ads and foo.adb. 13205 13206@item gnatfind main.ads:123 13207Find declarations and bodies for all entities that are referenced on 13208line 123 of main.ads. 13209 13210This is the same as @code{gnatfind "*":main.adb:123}. 13211 13212@item gnatfind ^mydir/^[mydir]^main.adb:123:45 13213Find the declaration for the entity referenced at column 45 in 13214line 123 of file main.adb in directory mydir. Note that it 13215is usual to omit the identifier name when the column is given, 13216since the column position identifies a unique reference. 13217 13218The column has to be the beginning of the identifier, and should not 13219point to any character in the middle of the identifier. 13220 13221@end table 13222 13223@c ********************************* 13224@node The GNAT Pretty-Printer gnatpp 13225@chapter The GNAT Pretty-Printer @command{gnatpp} 13226@findex gnatpp 13227@cindex Pretty-Printer 13228 13229@noindent 13230^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility 13231for source reformatting / pretty-printing. 13232It takes an Ada source file as input and generates a reformatted 13233version as output. 13234You can specify various style directives via switches; e.g., 13235identifier case conventions, rules of indentation, and comment layout. 13236 13237To produce a reformatted file, @command{gnatpp} generates and uses the ASIS 13238tree for the input source and thus requires the input to be syntactically and 13239semantically legal. 13240If this condition is not met, @command{gnatpp} will terminate with an 13241error message; no output file will be generated. 13242 13243@command{gnatpp} cannot process sources that contain 13244preprocessing directives. 13245 13246If the compilation unit 13247contained in the input source depends semantically upon units located 13248outside the current directory, you have to provide the source search path 13249when invoking @command{gnatpp}, if these units are contained in files with 13250names that do not follow the GNAT file naming rules, you have to provide 13251the configuration file describing the corresponding naming scheme; 13252see the description of the @command{gnatpp} 13253switches below. Another possibility is to use a project file and to 13254call @command{gnatpp} through the @command{gnat} driver 13255(see @ref{The GNAT Driver and Project Files}). 13256 13257The @command{gnatpp} command has the form 13258 13259@smallexample 13260@c $ gnatpp @ovar{switches} @var{filename} 13261@c Expanding @ovar macro inline (explanation in macro def comments) 13262$ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]} 13263@end smallexample 13264 13265@noindent 13266where 13267@itemize @bullet 13268@item 13269@var{switches} is an optional sequence of switches defining such properties as 13270the formatting rules, the source search path, and the destination for the 13271output source file 13272 13273@item 13274@var{filename} is the name (including the extension) of the source file to 13275reformat; ``wildcards'' or several file names on the same gnatpp command are 13276allowed. The file name may contain path information; it does not have to 13277follow the GNAT file naming rules 13278 13279@item 13280@samp{@var{gcc_switches}} is a list of switches for 13281@command{gcc}. They will be passed on to all compiler invocations made by 13282@command{gnatelim} to generate the ASIS trees. Here you can provide 13283@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path, 13284use the @option{-gnatec} switch to set the configuration file, 13285use the @option{-gnat05} switch if sources should be compiled in 13286Ada 2005 mode etc. 13287@end itemize 13288 13289@menu 13290* Switches for gnatpp:: 13291* Formatting Rules:: 13292@end menu 13293 13294@node Switches for gnatpp 13295@section Switches for @command{gnatpp} 13296 13297@noindent 13298The following subsections describe the various switches accepted by 13299@command{gnatpp}, organized by category. 13300 13301@ifclear vms 13302You specify a switch by supplying a name and generally also a value. 13303In many cases the values for a switch with a given name are incompatible with 13304each other 13305(for example the switch that controls the casing of a reserved word may have 13306exactly one value: upper case, lower case, or 13307mixed case) and thus exactly one such switch can be in effect for an 13308invocation of @command{gnatpp}. 13309If more than one is supplied, the last one is used. 13310However, some values for the same switch are mutually compatible. 13311You may supply several such switches to @command{gnatpp}, but then 13312each must be specified in full, with both the name and the value. 13313Abbreviated forms (the name appearing once, followed by each value) are 13314not permitted. 13315For example, to set 13316the alignment of the assignment delimiter both in declarations and in 13317assignment statements, you must write @option{-A2A3} 13318(or @option{-A2 -A3}), but not @option{-A23}. 13319@end ifclear 13320 13321@ifset vms 13322In many cases the set of options for a given qualifier are incompatible with 13323each other (for example the qualifier that controls the casing of a reserved 13324word may have exactly one option, which specifies either upper case, lower 13325case, or mixed case), and thus exactly one such option can be in effect for 13326an invocation of @command{gnatpp}. 13327If more than one is supplied, the last one is used. 13328However, some qualifiers have options that are mutually compatible, 13329and then you may then supply several such options when invoking 13330@command{gnatpp}. 13331@end ifset 13332 13333In most cases, it is obvious whether or not the 13334^values for a switch with a given name^options for a given qualifier^ 13335are compatible with each other. 13336When the semantics might not be evident, the summaries below explicitly 13337indicate the effect. 13338 13339@menu 13340* Alignment Control:: 13341* Casing Control:: 13342* Construct Layout Control:: 13343* General Text Layout Control:: 13344* Other Formatting Options:: 13345* Setting the Source Search Path:: 13346* Output File Control:: 13347* Other gnatpp Switches:: 13348@end menu 13349 13350@node Alignment Control 13351@subsection Alignment Control 13352@cindex Alignment control in @command{gnatpp} 13353 13354@noindent 13355Programs can be easier to read if certain constructs are vertically aligned. 13356By default all alignments are set ON. 13357Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to 13358OFF, and then use one or more of the other 13359^@option{-A@var{n}} switches^@option{/ALIGN} options^ 13360to activate alignment for specific constructs. 13361 13362@table @option 13363@cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp}) 13364 13365@ifset vms 13366@item /ALIGN=ON 13367Set all alignments to ON 13368@end ifset 13369 13370@item ^-A0^/ALIGN=OFF^ 13371Set all alignments to OFF 13372 13373@item ^-A1^/ALIGN=COLONS^ 13374Align @code{:} in declarations 13375 13376@item ^-A2^/ALIGN=DECLARATIONS^ 13377Align @code{:=} in initializations in declarations 13378 13379@item ^-A3^/ALIGN=STATEMENTS^ 13380Align @code{:=} in assignment statements 13381 13382@item ^-A4^/ALIGN=ARROWS^ 13383Align @code{=>} in associations 13384 13385@item ^-A5^/ALIGN=COMPONENT_CLAUSES^ 13386Align @code{at} keywords in the component clauses in record 13387representation clauses 13388@end table 13389 13390@noindent 13391The @option{^-A^/ALIGN^} switches are mutually compatible; any combination 13392is allowed. 13393 13394@node Casing Control 13395@subsection Casing Control 13396@cindex Casing control in @command{gnatpp} 13397 13398@noindent 13399@command{gnatpp} allows you to specify the casing for reserved words, 13400pragma names, attribute designators and identifiers. 13401For identifiers you may define a 13402general rule for name casing but also override this rule 13403via a set of dictionary files. 13404 13405Three types of casing are supported: lower case, upper case, and mixed case. 13406Lower and upper case are self-explanatory (but since some letters in 13407Latin1 and other GNAT-supported character sets 13408exist only in lower-case form, an upper case conversion will have no 13409effect on them.) 13410``Mixed case'' means that the first letter, and also each letter immediately 13411following an underscore, are converted to their uppercase forms; 13412all the other letters are converted to their lowercase forms. 13413 13414@table @option 13415@cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp}) 13416@item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^ 13417Attribute designators are lower case 13418 13419@item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^ 13420Attribute designators are upper case 13421 13422@item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^ 13423Attribute designators are mixed case (this is the default) 13424 13425@cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp}) 13426@item ^-kL^/KEYWORD_CASING=LOWER_CASE^ 13427Keywords (technically, these are known in Ada as @emph{reserved words}) are 13428lower case (this is the default) 13429 13430@item ^-kU^/KEYWORD_CASING=UPPER_CASE^ 13431Keywords are upper case 13432 13433@cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp}) 13434@item ^-nD^/NAME_CASING=AS_DECLARED^ 13435Name casing for defining occurrences are as they appear in the source file 13436(this is the default) 13437 13438@item ^-nU^/NAME_CASING=UPPER_CASE^ 13439Names are in upper case 13440 13441@item ^-nL^/NAME_CASING=LOWER_CASE^ 13442Names are in lower case 13443 13444@item ^-nM^/NAME_CASING=MIXED_CASE^ 13445Names are in mixed case 13446 13447@cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp}) 13448@item ^-neD^/ENUM_CASING=AS_DECLARED^ 13449Enumeration literal casing for defining occurrences are as they appear in the 13450source file. Overrides ^-n^/NAME_CASING^ casing setting. 13451 13452@item ^-neU^/ENUM_CASING=UPPER_CASE^ 13453Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing 13454setting. 13455 13456@item ^-neL^/ENUM_CASING=LOWER_CASE^ 13457Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing 13458setting. 13459 13460@item ^-neM^/ENUM_CASING=MIXED_CASE^ 13461Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing 13462setting. 13463 13464@cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp}) 13465@item ^-neD^/TYPE_CASING=AS_DECLARED^ 13466Names introduced by type and subtype declarations are always 13467cased as they appear in the declaration in the source file. 13468Overrides ^-n^/NAME_CASING^ casing setting. 13469 13470@item ^-ntU^/TYPE_CASING=UPPER_CASE^ 13471Names introduced by type and subtype declarations are always in 13472upper case. Overrides ^-n^/NAME_CASING^ casing setting. 13473 13474@item ^-ntL^/TYPE_CASING=LOWER_CASE^ 13475Names introduced by type and subtype declarations are always in 13476lower case. Overrides ^-n^/NAME_CASING^ casing setting. 13477 13478@item ^-ntM^/TYPE_CASING=MIXED_CASE^ 13479Names introduced by type and subtype declarations are always in 13480mixed case. Overrides ^-n^/NAME_CASING^ casing setting. 13481 13482@item ^-nnU^/NUMBER_CASING=UPPER_CASE^ 13483Names introduced by number declarations are always in 13484upper case. Overrides ^-n^/NAME_CASING^ casing setting. 13485 13486@item ^-nnL^/NUMBER_CASING=LOWER_CASE^ 13487Names introduced by number declarations are always in 13488lower case. Overrides ^-n^/NAME_CASING^ casing setting. 13489 13490@item ^-nnM^/NUMBER_CASING=MIXED_CASE^ 13491Names introduced by number declarations are always in 13492mixed case. Overrides ^-n^/NAME_CASING^ casing setting. 13493 13494@cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp}) 13495@item ^-pL^/PRAGMA_CASING=LOWER_CASE^ 13496Pragma names are lower case 13497 13498@item ^-pU^/PRAGMA_CASING=UPPER_CASE^ 13499Pragma names are upper case 13500 13501@item ^-pM^/PRAGMA_CASING=MIXED_CASE^ 13502Pragma names are mixed case (this is the default) 13503 13504@item ^-D@var{file}^/DICTIONARY=@var{file}^ 13505@cindex @option{^-D^/DICTIONARY^} (@command{gnatpp}) 13506Use @var{file} as a @emph{dictionary file} that defines 13507the casing for a set of specified names, 13508thereby overriding the effect on these names by 13509any explicit or implicit 13510^-n^/NAME_CASING^ switch. 13511To supply more than one dictionary file, 13512use ^several @option{-D} switches^a list of files as options^. 13513 13514@noindent 13515@option{gnatpp} implicitly uses a @emph{default dictionary file} 13516to define the casing for the Ada predefined names and 13517the names declared in the GNAT libraries. 13518 13519@item ^-D-^/SPECIFIC_CASING^ 13520@cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp}) 13521Do not use the default dictionary file; 13522instead, use the casing 13523defined by a @option{^-n^/NAME_CASING^} switch and any explicit 13524dictionary file(s) 13525@end table 13526 13527@noindent 13528The structure of a dictionary file, and details on the conventions 13529used in the default dictionary file, are defined in @ref{Name Casing}. 13530 13531The @option{^-D-^/SPECIFIC_CASING^} and 13532@option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually 13533compatible. 13534 13535@node Construct Layout Control 13536@subsection Construct Layout Control 13537@cindex Layout control in @command{gnatpp} 13538 13539@noindent 13540This group of @command{gnatpp} switches controls the layout of comments and 13541complex syntactic constructs. See @ref{Formatting Comments} for details 13542on their effect. 13543 13544@table @option 13545@cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp}) 13546@item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^ 13547All the comments remain unchanged 13548 13549@item ^-c1^/COMMENTS_LAYOUT=DEFAULT^ 13550GNAT-style comment line indentation (this is the default). 13551 13552@item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^ 13553Reference-manual comment line indentation. 13554 13555@item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^ 13556GNAT-style comment beginning 13557 13558@item ^-c4^/COMMENTS_LAYOUT=REFORMAT^ 13559Reformat comment blocks 13560 13561@item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^ 13562Keep unchanged special form comments 13563 13564@cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp}) 13565@item ^-l1^/CONSTRUCT_LAYOUT=GNAT^ 13566GNAT-style layout (this is the default) 13567 13568@item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^ 13569Compact layout 13570 13571@item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^ 13572Uncompact layout 13573 13574@cindex @option{^-N^/NOTABS^} (@command{gnatpp}) 13575@item ^-N^/NOTABS^ 13576All the VT characters are removed from the comment text. All the HT characters 13577are expanded with the sequences of space characters to get to the next tab 13578stops. 13579 13580@cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp}) 13581@item ^--no-separate-is^/NO_SEPARATE_IS^ 13582Do not place the keyword @code{is} on a separate line in a subprogram body in 13583case if the spec occupies more than one line. 13584 13585@cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp}) 13586@item ^--separate-label^/SEPARATE_LABEL^ 13587Place statement label(s) on a separate line, with the following statement 13588on the next line. 13589 13590@cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp}) 13591@item ^--separate-loop-then^/SEPARATE_LOOP_THEN^ 13592Place the keyword @code{loop} in FOR and WHILE loop statements and the 13593keyword @code{then} in IF statements on a separate line. 13594 13595@cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp}) 13596@item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^ 13597Do not place the keyword @code{loop} in FOR and WHILE loop statements and the 13598keyword @code{then} in IF statements on a separate line. This option is 13599incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option. 13600 13601@cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp}) 13602@item ^--use-on-new-line^/USE_ON_NEW_LINE^ 13603Start each USE clause in a context clause from a separate line. 13604 13605@cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp}) 13606@item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^ 13607Use a separate line for a loop or block statement name, but do not use an extra 13608indentation level for the statement itself. 13609 13610@end table 13611 13612@ifclear vms 13613@noindent 13614The @option{-c1} and @option{-c2} switches are incompatible. 13615The @option{-c3} and @option{-c4} switches are compatible with each other and 13616also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all 13617the other comment formatting switches. 13618 13619The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible. 13620@end ifclear 13621 13622@ifset vms 13623@noindent 13624For the @option{/COMMENTS_LAYOUT} qualifier: 13625@itemize @bullet 13626@item 13627The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible. 13628@item 13629The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with 13630each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}. 13631@end itemize 13632 13633@noindent 13634The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the 13635@option{/CONSTRUCT_LAYOUT} qualifier are incompatible. 13636@end ifset 13637 13638@node General Text Layout Control 13639@subsection General Text Layout Control 13640 13641@noindent 13642These switches allow control over line length and indentation. 13643 13644@table @option 13645@item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^ 13646@cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp}) 13647Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79 13648 13649@item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^ 13650@cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp}) 13651Indentation level, @var{nnn} from 1@dots{}9, the default value is 3 13652 13653@item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^ 13654@cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp}) 13655Indentation level for continuation lines (relative to the line being 13656continued), @var{nnn} from 1@dots{}9. 13657The default 13658value is one less than the (normal) indentation level, unless the 13659indentation is set to 1 (in which case the default value for continuation 13660line indentation is also 1) 13661@end table 13662 13663@node Other Formatting Options 13664@subsection Other Formatting Options 13665 13666@noindent 13667These switches control the inclusion of missing end/exit labels, and 13668the indentation level in @b{case} statements. 13669 13670@table @option 13671@item ^-e^/NO_MISSED_LABELS^ 13672@cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp}) 13673Do not insert missing end/exit labels. An end label is the name of 13674a construct that may optionally be repeated at the end of the 13675construct's declaration; 13676e.g., the names of packages, subprograms, and tasks. 13677An exit label is the name of a loop that may appear as target 13678of an exit statement within the loop. 13679By default, @command{gnatpp} inserts these end/exit labels when 13680they are absent from the original source. This option suppresses such 13681insertion, so that the formatted source reflects the original. 13682 13683@item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^ 13684@cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp}) 13685Insert a Form Feed character after a pragma Page. 13686 13687@item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^ 13688@cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp}) 13689Do not use an additional indentation level for @b{case} alternatives 13690and variants if there are @var{nnn} or more (the default 13691value is 10). 13692If @var{nnn} is 0, an additional indentation level is 13693used for @b{case} alternatives and variants regardless of their number. 13694 13695@item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^ 13696@cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp}) 13697If the number of parameter associations is greater than @var{nnn} and if at 13698least one association uses named notation, start each association from 13699a new line. If @var{nnn} is 0, no check for the number of associations 13700is made, this is the default. 13701 13702@item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^ 13703@cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp}) 13704If the number of parameter specifications is greater than @var{nnn} 13705(or equal to @var{nnn} in case of a function), start each specification from 13706a new line. The default for @var{nnn} is 3. 13707@end table 13708 13709@node Setting the Source Search Path 13710@subsection Setting the Source Search Path 13711 13712@noindent 13713To define the search path for the input source file, @command{gnatpp} 13714uses the same switches as the GNAT compiler, with the same effects. 13715 13716@table @option 13717@item ^-I^/SEARCH=^@var{dir} 13718@cindex @option{^-I^/SEARCH^} (@code{gnatpp}) 13719The same as the corresponding gcc switch 13720 13721@item ^-I-^/NOCURRENT_DIRECTORY^ 13722@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp}) 13723The same as the corresponding gcc switch 13724 13725@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path} 13726@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp}) 13727The same as the corresponding gcc switch 13728 13729@item ^--RTS^/RUNTIME_SYSTEM^=@var{path} 13730@cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp}) 13731The same as the corresponding gcc switch 13732 13733@end table 13734 13735@node Output File Control 13736@subsection Output File Control 13737 13738@noindent 13739By default the output is sent to the file whose name is obtained by appending 13740the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file 13741(if the file with this name already exists, it is unconditionally overwritten). 13742Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then 13743@command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^} 13744as output file. 13745The output may be redirected by the following switches: 13746 13747@table @option 13748@item ^-pipe^/STANDARD_OUTPUT^ 13749@cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp}) 13750Send the output to @code{Standard_Output} 13751 13752@item ^-o @var{output_file}^/OUTPUT=@var{output_file}^ 13753@cindex @option{^-o^/OUTPUT^} (@code{gnatpp}) 13754Write the output into @var{output_file}. 13755If @var{output_file} already exists, @command{gnatpp} terminates without 13756reading or processing the input file. 13757 13758@item ^-of ^/FORCED_OUTPUT=^@var{output_file} 13759@cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp}) 13760Write the output into @var{output_file}, overwriting the existing file 13761(if one is present). 13762 13763@item ^-r^/REPLACE^ 13764@cindex @option{^-r^/REPLACE^} (@code{gnatpp}) 13765Replace the input source file with the reformatted output, and copy the 13766original input source into the file whose name is obtained by appending the 13767^@file{.npp}^@file{$NPP}^ suffix to the name of the input file. 13768If a file with this name already exists, @command{gnatpp} terminates without 13769reading or processing the input file. 13770 13771@item ^-rf^/OVERRIDING_REPLACE^ 13772@cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp}) 13773Like @option{^-r^/REPLACE^} except that if the file with the specified name 13774already exists, it is overwritten. 13775 13776@item ^-rnb^/REPLACE_NO_BACKUP^ 13777@cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp}) 13778Replace the input source file with the reformatted output without 13779creating any backup copy of the input source. 13780 13781@item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^ 13782@cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp}) 13783Specifies the format of the reformatted output file. The @var{xxx} 13784^string specified with the switch^option^ may be either 13785@itemize @bullet 13786@item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters 13787@item ``@option{^crlf^CRLF^}'' 13788the same as @option{^crlf^CRLF^} 13789@item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character 13790@item ``@option{^lf^LF^}'' 13791the same as @option{^unix^UNIX^} 13792@end itemize 13793 13794@item ^-W^/RESULT_ENCODING=^@var{e} 13795@cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp}) 13796Specify the wide character encoding method used to write the code in the 13797result file 13798@var{e} is one of the following: 13799 13800@itemize @bullet 13801 13802@item ^h^HEX^ 13803Hex encoding 13804 13805@item ^u^UPPER^ 13806Upper half encoding 13807 13808@item ^s^SHIFT_JIS^ 13809Shift/JIS encoding 13810 13811@item ^e^EUC^ 13812EUC encoding 13813 13814@item ^8^UTF8^ 13815UTF-8 encoding 13816 13817@item ^b^BRACKETS^ 13818Brackets encoding (default value) 13819@end itemize 13820 13821@end table 13822 13823@noindent 13824Options @option{^-pipe^/STANDARD_OUTPUT^}, 13825@option{^-o^/OUTPUT^} and 13826@option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp 13827contains only one file to reformat. 13828Option 13829@option{^--eol^/END_OF_LINE^} 13830and 13831@option{^-W^/RESULT_ENCODING^} 13832cannot be used together 13833with @option{^-pipe^/STANDARD_OUTPUT^} option. 13834 13835@node Other gnatpp Switches 13836@subsection Other @code{gnatpp} Switches 13837 13838@noindent 13839The additional @command{gnatpp} switches are defined in this subsection. 13840 13841@table @option 13842@item ^-files @var{filename}^/FILES=@var{filename}^ 13843@cindex @option{^-files^/FILES^} (@code{gnatpp}) 13844Take the argument source files from the specified file. This file should be an 13845ordinary text file containing file names separated by spaces or 13846line breaks. You can use this switch more than once in the same call to 13847@command{gnatpp}. You also can combine this switch with an explicit list of 13848files. 13849 13850@item ^-v^/VERBOSE^ 13851@cindex @option{^-v^/VERBOSE^} (@code{gnatpp}) 13852Verbose mode; 13853@command{gnatpp} generates version information and then 13854a trace of the actions it takes to produce or obtain the ASIS tree. 13855 13856@item ^-w^/WARNINGS^ 13857@cindex @option{^-w^/WARNINGS^} (@code{gnatpp}) 13858Warning mode; 13859@command{gnatpp} generates a warning whenever it cannot provide 13860a required layout in the result source. 13861@end table 13862 13863@node Formatting Rules 13864@section Formatting Rules 13865 13866@noindent 13867The following subsections show how @command{gnatpp} treats ``white space'', 13868comments, program layout, and name casing. 13869They provide the detailed descriptions of the switches shown above. 13870 13871@menu 13872* White Space and Empty Lines:: 13873* Formatting Comments:: 13874* Construct Layout:: 13875* Name Casing:: 13876@end menu 13877 13878@node White Space and Empty Lines 13879@subsection White Space and Empty Lines 13880 13881@noindent 13882@command{gnatpp} does not have an option to control space characters. 13883It will add or remove spaces according to the style illustrated by the 13884examples in the @cite{Ada Reference Manual}. 13885 13886The only format effectors 13887(see @cite{Ada Reference Manual}, paragraph 2.1(13)) 13888that will appear in the output file are platform-specific line breaks, 13889and also format effectors within (but not at the end of) comments. 13890In particular, each horizontal tab character that is not inside 13891a comment will be treated as a space and thus will appear in the 13892output file as zero or more spaces depending on 13893the reformatting of the line in which it appears. 13894The only exception is a Form Feed character, which is inserted after a 13895pragma @code{Page} when @option{-ff} is set. 13896 13897The output file will contain no lines with trailing ``white space'' (spaces, 13898format effectors). 13899 13900Empty lines in the original source are preserved 13901only if they separate declarations or statements. 13902In such contexts, a 13903sequence of two or more empty lines is replaced by exactly one empty line. 13904Note that a blank line will be removed if it separates two ``comment blocks'' 13905(a comment block is a sequence of whole-line comments). 13906In order to preserve a visual separation between comment blocks, use an 13907``empty comment'' (a line comprising only hyphens) rather than an empty line. 13908Likewise, if for some reason you wish to have a sequence of empty lines, 13909use a sequence of empty comments instead. 13910 13911@node Formatting Comments 13912@subsection Formatting Comments 13913 13914@noindent 13915Comments in Ada code are of two kinds: 13916@itemize @bullet 13917@item 13918a @emph{whole-line comment}, which appears by itself (possibly preceded by 13919``white space'') on a line 13920 13921@item 13922an @emph{end-of-line comment}, which follows some other Ada lexical element 13923on the same line. 13924@end itemize 13925 13926@noindent 13927The indentation of a whole-line comment is that of either 13928the preceding or following line in 13929the formatted source, depending on switch settings as will be described below. 13930 13931For an end-of-line comment, @command{gnatpp} leaves the same number of spaces 13932between the end of the preceding Ada lexical element and the beginning 13933of the comment as appear in the original source, 13934unless either the comment has to be split to 13935satisfy the line length limitation, or else the next line contains a 13936whole line comment that is considered a continuation of this end-of-line 13937comment (because it starts at the same position). 13938In the latter two 13939cases, the start of the end-of-line comment is moved right to the nearest 13940multiple of the indentation level. 13941This may result in a ``line overflow'' (the right-shifted comment extending 13942beyond the maximum line length), in which case the comment is split as 13943described below. 13944 13945There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^} 13946(GNAT-style comment line indentation) 13947and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^} 13948(reference-manual comment line indentation). 13949With reference-manual style, a whole-line comment is indented as if it 13950were a declaration or statement at the same place 13951(i.e., according to the indentation of the preceding line(s)). 13952With GNAT style, a whole-line comment that is immediately followed by an 13953@b{if} or @b{case} statement alternative, a record variant, or the reserved 13954word @b{begin}, is indented based on the construct that follows it. 13955 13956For example: 13957@smallexample @c ada 13958@cartouche 13959if A then 13960 null; 13961 -- some comment 13962else 13963 null; 13964end if; 13965@end cartouche 13966@end smallexample 13967 13968@noindent 13969Reference-manual indentation produces: 13970 13971@smallexample @c ada 13972@cartouche 13973if A then 13974 null; 13975 -- some comment 13976else 13977 null; 13978end if; 13979@end cartouche 13980@end smallexample 13981 13982@noindent 13983while GNAT-style indentation produces: 13984 13985@smallexample @c ada 13986@cartouche 13987if A then 13988 null; 13989-- some comment 13990else 13991 null; 13992end if; 13993@end cartouche 13994@end smallexample 13995 13996@noindent 13997The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch 13998(GNAT style comment beginning) has the following 13999effect: 14000 14001@itemize @bullet 14002@item 14003For each whole-line comment that does not end with two hyphens, 14004@command{gnatpp} inserts spaces if necessary after the starting two hyphens 14005to ensure that there are at least two spaces between these hyphens and the 14006first non-blank character of the comment. 14007@end itemize 14008 14009@noindent 14010For an end-of-line comment, if in the original source the next line is a 14011whole-line comment that starts at the same position 14012as the end-of-line comment, 14013then the whole-line comment (and all whole-line comments 14014that follow it and that start at the same position) 14015will start at this position in the output file. 14016 14017@noindent 14018That is, if in the original source we have: 14019 14020@smallexample @c ada 14021@cartouche 14022begin 14023A := B + C; -- B must be in the range Low1..High1 14024 -- C must be in the range Low2..High2 14025 --B+C will be in the range Low1+Low2..High1+High2 14026X := X + 1; 14027@end cartouche 14028@end smallexample 14029 14030@noindent 14031Then in the formatted source we get 14032 14033@smallexample @c ada 14034@cartouche 14035begin 14036 A := B + C; -- B must be in the range Low1..High1 14037 -- C must be in the range Low2..High2 14038 -- B+C will be in the range Low1+Low2..High1+High2 14039 X := X + 1; 14040@end cartouche 14041@end smallexample 14042 14043@noindent 14044A comment that exceeds the line length limit will be split. 14045Unless switch 14046@option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and 14047the line belongs to a reformattable block, splitting the line generates a 14048@command{gnatpp} warning. 14049The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line 14050comments may be reformatted in typical 14051word processor style (that is, moving words between lines and putting as 14052many words in a line as possible). 14053 14054@noindent 14055The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments 14056that has a special format (that is, a character that is neither a letter nor digit 14057not white space nor line break immediately following the leading @code{--} of 14058the comment) should be without any change moved from the argument source 14059into reformatted source. This switch allows to preserve comments that are used 14060as a special marks in the code (e.g.@: SPARK annotation). 14061 14062@node Construct Layout 14063@subsection Construct Layout 14064 14065@noindent 14066In several cases the suggested layout in the Ada Reference Manual includes 14067an extra level of indentation that many programmers prefer to avoid. The 14068affected cases include: 14069 14070@itemize @bullet 14071 14072@item Record type declaration (RM 3.8) 14073 14074@item Record representation clause (RM 13.5.1) 14075 14076@item Loop statement in case if a loop has a statement identifier (RM 5.6) 14077 14078@item Block statement in case if a block has a statement identifier (RM 5.6) 14079@end itemize 14080 14081@noindent 14082In compact mode (when GNAT style layout or compact layout is set), 14083the pretty printer uses one level of indentation instead 14084of two. This is achieved in the record definition and record representation 14085clause cases by putting the @code{record} keyword on the same line as the 14086start of the declaration or representation clause, and in the block and loop 14087case by putting the block or loop header on the same line as the statement 14088identifier. 14089 14090@noindent 14091The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^} 14092and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} 14093layout on the one hand, and uncompact layout 14094@option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand, 14095can be illustrated by the following examples: 14096 14097@iftex 14098@cartouche 14099@multitable @columnfractions .5 .5 14100@item @i{GNAT style, compact layout} @tab @i{Uncompact layout} 14101 14102@item 14103@smallexample @c ada 14104type q is record 14105 a : integer; 14106 b : integer; 14107end record; 14108@end smallexample 14109@tab 14110@smallexample @c ada 14111type q is 14112 record 14113 a : integer; 14114 b : integer; 14115 end record; 14116@end smallexample 14117 14118@item 14119@smallexample @c ada 14120for q use record 14121 a at 0 range 0 .. 31; 14122 b at 4 range 0 .. 31; 14123end record; 14124@end smallexample 14125@tab 14126@smallexample @c ada 14127for q use 14128 record 14129 a at 0 range 0 .. 31; 14130 b at 4 range 0 .. 31; 14131 end record; 14132@end smallexample 14133 14134@item 14135@smallexample @c ada 14136Block : declare 14137 A : Integer := 3; 14138begin 14139 Proc (A, A); 14140end Block; 14141@end smallexample 14142@tab 14143@smallexample @c ada 14144Block : 14145 declare 14146 A : Integer := 3; 14147 begin 14148 Proc (A, A); 14149 end Block; 14150@end smallexample 14151 14152@item 14153@smallexample @c ada 14154Clear : for J in 1 .. 10 loop 14155 A (J) := 0; 14156end loop Clear; 14157@end smallexample 14158@tab 14159@smallexample @c ada 14160Clear : 14161 for J in 1 .. 10 loop 14162 A (J) := 0; 14163 end loop Clear; 14164@end smallexample 14165@end multitable 14166@end cartouche 14167@end iftex 14168 14169@ifnottex 14170@smallexample 14171@cartouche 14172GNAT style, compact layout Uncompact layout 14173 14174type q is record type q is 14175 a : integer; record 14176 b : integer; a : integer; 14177end record; b : integer; 14178 end record; 14179 14180for q use record for q use 14181 a at 0 range 0 .. 31; record 14182 b at 4 range 0 .. 31; a at 0 range 0 .. 31; 14183end record; b at 4 range 0 .. 31; 14184 end record; 14185 14186Block : declare Block : 14187 A : Integer := 3; declare 14188begin A : Integer := 3; 14189 Proc (A, A); begin 14190end Block; Proc (A, A); 14191 end Block; 14192 14193Clear : for J in 1 .. 10 loop Clear : 14194 A (J) := 0; for J in 1 .. 10 loop 14195end loop Clear; A (J) := 0; 14196 end loop Clear; 14197@end cartouche 14198@end smallexample 14199@end ifnottex 14200 14201@noindent 14202A further difference between GNAT style layout and compact layout is that 14203GNAT style layout inserts empty lines as separation for 14204compound statements, return statements and bodies. 14205 14206Note that the layout specified by 14207@option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} 14208for named block and loop statements overrides the layout defined by these 14209constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}, 14210@option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or 14211@option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option. 14212 14213@node Name Casing 14214@subsection Name Casing 14215 14216@noindent 14217@command{gnatpp} always converts the usage occurrence of a (simple) name to 14218the same casing as the corresponding defining identifier. 14219 14220You control the casing for defining occurrences via the 14221@option{^-n^/NAME_CASING^} switch. 14222@ifclear vms 14223With @option{-nD} (``as declared'', which is the default), 14224@end ifclear 14225@ifset vms 14226With @option{/NAME_CASING=AS_DECLARED}, which is the default, 14227@end ifset 14228defining occurrences appear exactly as in the source file 14229where they are declared. 14230The other ^values for this switch^options for this qualifier^ --- 14231@option{^-nU^UPPER_CASE^}, 14232@option{^-nL^LOWER_CASE^}, 14233@option{^-nM^MIXED_CASE^} --- 14234result in 14235^upper, lower, or mixed case, respectively^the corresponding casing^. 14236If @command{gnatpp} changes the casing of a defining 14237occurrence, it analogously changes the casing of all the 14238usage occurrences of this name. 14239 14240If the defining occurrence of a name is not in the source compilation unit 14241currently being processed by @command{gnatpp}, the casing of each reference to 14242this name is changed according to the value of the @option{^-n^/NAME_CASING^} 14243switch (subject to the dictionary file mechanism described below). 14244Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch 14245had affected the 14246casing for the defining occurrence of the name. 14247 14248Some names may need to be spelled with casing conventions that are not 14249covered by the upper-, lower-, and mixed-case transformations. 14250You can arrange correct casing by placing such names in a 14251@emph{dictionary file}, 14252and then supplying a @option{^-D^/DICTIONARY^} switch. 14253The casing of names from dictionary files overrides 14254any @option{^-n^/NAME_CASING^} switch. 14255 14256To handle the casing of Ada predefined names and the names from GNAT libraries, 14257@command{gnatpp} assumes a default dictionary file. 14258The name of each predefined entity is spelled with the same casing as is used 14259for the entity in the @cite{Ada Reference Manual}. 14260The name of each entity in the GNAT libraries is spelled with the same casing 14261as is used in the declaration of that entity. 14262 14263The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the 14264default dictionary file. 14265Instead, the casing for predefined and GNAT-defined names will be established 14266by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files. 14267For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib} 14268will appear as just shown, 14269even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. 14270To ensure that even such names are rendered in uppercase, 14271additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch 14272(or else, less conveniently, place these names in upper case in a dictionary 14273file). 14274 14275A dictionary file is 14276a plain text file; each line in this file can be either a blank line 14277(containing only space characters and ASCII.HT characters), an Ada comment 14278line, or the specification of exactly one @emph{casing schema}. 14279 14280A casing schema is a string that has the following syntax: 14281 14282@smallexample 14283@cartouche 14284 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}* 14285 14286 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@} 14287@end cartouche 14288@end smallexample 14289 14290@noindent 14291(See @cite{Ada Reference Manual}, Section 2.3) for the definition of the 14292@var{identifier} lexical element and the @var{letter_or_digit} category.) 14293 14294The casing schema string can be followed by white space and/or an Ada-style 14295comment; any amount of white space is allowed before the string. 14296 14297If a dictionary file is passed as 14298@ifclear vms 14299the value of a @option{-D@var{file}} switch 14300@end ifclear 14301@ifset vms 14302an option to the @option{/DICTIONARY} qualifier 14303@end ifset 14304then for every 14305simple name and every identifier, @command{gnatpp} checks if the dictionary 14306defines the casing for the name or for some of its parts (the term ``subword'' 14307is used below to denote the part of a name which is delimited by ``_'' or by 14308the beginning or end of the word and which does not contain any ``_'' inside): 14309 14310@itemize @bullet 14311@item 14312if the whole name is in the dictionary, @command{gnatpp} uses for this name 14313the casing defined by the dictionary; no subwords are checked for this word 14314 14315@item 14316for every subword @command{gnatpp} checks if the dictionary contains the 14317corresponding string of the form @code{*@var{simple_identifier}*}, 14318and if it does, the casing of this @var{simple_identifier} is used 14319for this subword 14320 14321@item 14322if the whole name does not contain any ``_'' inside, and if for this name 14323the dictionary contains two entries - one of the form @var{identifier}, 14324and another - of the form *@var{simple_identifier}*, then the first one 14325is applied to define the casing of this name 14326 14327@item 14328if more than one dictionary file is passed as @command{gnatpp} switches, each 14329dictionary adds new casing exceptions and overrides all the existing casing 14330exceptions set by the previous dictionaries 14331 14332@item 14333when @command{gnatpp} checks if the word or subword is in the dictionary, 14334this check is not case sensitive 14335@end itemize 14336 14337@noindent 14338For example, suppose we have the following source to reformat: 14339 14340@smallexample @c ada 14341@cartouche 14342procedure test is 14343 name1 : integer := 1; 14344 name4_name3_name2 : integer := 2; 14345 name2_name3_name4 : Boolean; 14346 name1_var : Float; 14347begin 14348 name2_name3_name4 := name4_name3_name2 > name1; 14349end; 14350@end cartouche 14351@end smallexample 14352 14353@noindent 14354And suppose we have two dictionaries: 14355 14356@smallexample 14357@cartouche 14358@i{dict1:} 14359 NAME1 14360 *NaMe3* 14361 *Name1* 14362@end cartouche 14363 14364@cartouche 14365@i{dict2:} 14366 *NAME3* 14367@end cartouche 14368@end smallexample 14369 14370@noindent 14371If @command{gnatpp} is called with the following switches: 14372 14373@smallexample 14374@ifclear vms 14375@command{gnatpp -nM -D dict1 -D dict2 test.adb} 14376@end ifclear 14377@ifset vms 14378@command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)} 14379@end ifset 14380@end smallexample 14381 14382@noindent 14383then we will get the following name casing in the @command{gnatpp} output: 14384 14385@smallexample @c ada 14386@cartouche 14387procedure Test is 14388 NAME1 : Integer := 1; 14389 Name4_NAME3_Name2 : Integer := 2; 14390 Name2_NAME3_Name4 : Boolean; 14391 Name1_Var : Float; 14392begin 14393 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1; 14394end Test; 14395@end cartouche 14396@end smallexample 14397 14398@c ********************************* 14399@node The GNAT Metric Tool gnatmetric 14400@chapter The GNAT Metric Tool @command{gnatmetric} 14401@findex gnatmetric 14402@cindex Metric tool 14403 14404@noindent 14405^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility 14406for computing various program metrics. 14407It takes an Ada source file as input and generates a file containing the 14408metrics data as output. Various switches control which 14409metrics are computed and output. 14410 14411@command{gnatmetric} generates and uses the ASIS 14412tree for the input source and thus requires the input to be syntactically and 14413semantically legal. 14414If this condition is not met, @command{gnatmetric} will generate 14415an error message; no metric information for this file will be 14416computed and reported. 14417 14418If the compilation unit contained in the input source depends semantically 14419upon units in files located outside the current directory, you have to provide 14420the source search path when invoking @command{gnatmetric}. 14421If it depends semantically upon units that are contained 14422in files with names that do not follow the GNAT file naming rules, you have to 14423provide the configuration file describing the corresponding naming scheme (see 14424the description of the @command{gnatmetric} switches below.) 14425Alternatively, you may use a project file and invoke @command{gnatmetric} 14426through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}). 14427 14428The @command{gnatmetric} command has the form 14429 14430@smallexample 14431@c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]} 14432@c Expanding @ovar macro inline (explanation in macro def comments) 14433$ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]} 14434@end smallexample 14435 14436@noindent 14437where 14438@itemize @bullet 14439@item 14440@var{switches} specify the metrics to compute and define the destination for 14441the output 14442 14443@item 14444Each @var{filename} is the name (including the extension) of a source 14445file to process. ``Wildcards'' are allowed, and 14446the file name may contain path information. 14447If no @var{filename} is supplied, then the @var{switches} list must contain 14448at least one 14449@option{-files} switch (@pxref{Other gnatmetric Switches}). 14450Including both a @option{-files} switch and one or more 14451@var{filename} arguments is permitted. 14452 14453@item 14454@samp{@var{gcc_switches}} is a list of switches for 14455@command{gcc}. They will be passed on to all compiler invocations made by 14456@command{gnatmetric} to generate the ASIS trees. Here you can provide 14457@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path, 14458and use the @option{-gnatec} switch to set the configuration file, 14459use the @option{-gnat05} switch if sources should be compiled in 14460Ada 2005 mode etc. 14461@end itemize 14462 14463@menu 14464* Switches for gnatmetric:: 14465@end menu 14466 14467@node Switches for gnatmetric 14468@section Switches for @command{gnatmetric} 14469 14470@noindent 14471The following subsections describe the various switches accepted by 14472@command{gnatmetric}, organized by category. 14473 14474@menu 14475* Output Files Control:: 14476* Disable Metrics For Local Units:: 14477* Specifying a set of metrics to compute:: 14478* Other gnatmetric Switches:: 14479* Generate project-wide metrics:: 14480@end menu 14481 14482@node Output Files Control 14483@subsection Output File Control 14484@cindex Output file control in @command{gnatmetric} 14485 14486@noindent 14487@command{gnatmetric} has two output formats. It can generate a 14488textual (human-readable) form, and also XML. By default only textual 14489output is generated. 14490 14491When generating the output in textual form, @command{gnatmetric} creates 14492for each Ada source file a corresponding text file 14493containing the computed metrics, except for the case when the set of metrics 14494specified by gnatmetric parameters consists only of metrics that are computed 14495for the whole set of analyzed sources, but not for each Ada source. 14496By default, this file is placed in the same directory as where the source 14497file is located, and its name is obtained 14498by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the 14499input file. 14500 14501All the output information generated in XML format is placed in a single 14502file. By default this file is placed in the current directory and has the 14503name ^@file{metrix.xml}^@file{METRIX$XML}^. 14504 14505Some of the computed metrics are summed over the units passed to 14506@command{gnatmetric}; for example, the total number of lines of code. 14507By default this information is sent to @file{stdout}, but a file 14508can be specified with the @option{-og} switch. 14509 14510The following switches control the @command{gnatmetric} output: 14511 14512@table @option 14513@cindex @option{^-x^/XML^} (@command{gnatmetric}) 14514@item ^-x^/XML^ 14515Generate the XML output 14516 14517@cindex @option{^-xs^/XSD^} (@command{gnatmetric}) 14518@item ^-xs^/XSD^ 14519Generate the XML output and the XML schema file that describes the structure 14520of the XML metric report, this schema is assigned to the XML file. The schema 14521file has the same name as the XML output file with @file{.xml} suffix replaced 14522with @file{.xsd} 14523 14524@cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric}) 14525@item ^-nt^/NO_TEXT^ 14526Do not generate the output in text form (implies @option{^-x^/XML^}) 14527 14528@cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric}) 14529@item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^ 14530Put text files with detailed metrics into @var{output_dir} 14531 14532@cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric}) 14533@item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^ 14534Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^ 14535in the name of the output file. 14536 14537@cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric}) 14538@item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^ 14539Put global metrics into @var{file_name} 14540 14541@cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric}) 14542@item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^ 14543Put the XML output into @var{file_name} (also implies @option{^-x^/XML^}) 14544 14545@cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric}) 14546@item ^-sfn^/SHORT_SOURCE_FILE_NAME^ 14547Use ``short'' source file names in the output. (The @command{gnatmetric} 14548output includes the name(s) of the Ada source file(s) from which the metrics 14549are computed. By default each name includes the absolute path. The 14550@option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric} 14551to exclude all directory information from the file names that are output.) 14552 14553@end table 14554 14555@node Disable Metrics For Local Units 14556@subsection Disable Metrics For Local Units 14557@cindex Disable Metrics For Local Units in @command{gnatmetric} 14558 14559@noindent 14560@command{gnatmetric} relies on the GNAT compilation model @minus{} 14561one compilation 14562unit per one source file. It computes line metrics for the whole source 14563file, and it also computes syntax 14564and complexity metrics for the file's outermost unit. 14565 14566By default, @command{gnatmetric} will also compute all metrics for certain 14567kinds of locally declared program units: 14568 14569@itemize @bullet 14570@item 14571subprogram (and generic subprogram) bodies; 14572 14573@item 14574package (and generic package) specs and bodies; 14575 14576@item 14577task object and type specifications and bodies; 14578 14579@item 14580protected object and type specifications and bodies. 14581@end itemize 14582 14583@noindent 14584These kinds of entities will be referred to as 14585@emph{eligible local program units}, or simply @emph{eligible local units}, 14586@cindex Eligible local unit (for @command{gnatmetric}) 14587in the discussion below. 14588 14589Note that a subprogram declaration, generic instantiation, 14590or renaming declaration only receives metrics 14591computation when it appear as the outermost entity 14592in a source file. 14593 14594Suppression of metrics computation for eligible local units can be 14595obtained via the following switch: 14596 14597@table @option 14598@cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric}) 14599@item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^ 14600Do not compute detailed metrics for eligible local program units 14601 14602@end table 14603 14604@node Specifying a set of metrics to compute 14605@subsection Specifying a set of metrics to compute 14606 14607@noindent 14608By default all the metrics are computed and reported. The switches 14609described in this subsection allow you to control, on an individual 14610basis, whether metrics are computed and 14611reported. If at least one positive metric 14612switch is specified (that is, a switch that defines that a given 14613metric or set of metrics is to be computed), then only 14614explicitly specified metrics are reported. 14615 14616@menu 14617* Line Metrics Control:: 14618* Syntax Metrics Control:: 14619* Complexity Metrics Control:: 14620* Coupling Metrics Control:: 14621@end menu 14622 14623@node Line Metrics Control 14624@subsubsection Line Metrics Control 14625@cindex Line metrics control in @command{gnatmetric} 14626 14627@noindent 14628For any (legal) source file, and for each of its 14629eligible local program units, @command{gnatmetric} computes the following 14630metrics: 14631 14632@itemize @bullet 14633@item 14634the total number of lines; 14635 14636@item 14637the total number of code lines (i.e., non-blank lines that are not comments) 14638 14639@item 14640the number of comment lines 14641 14642@item 14643the number of code lines containing end-of-line comments; 14644 14645@item 14646the comment percentage: the ratio between the number of lines that contain 14647comments and the number of all non-blank lines, expressed as a percentage; 14648 14649@item 14650the number of empty lines and lines containing only space characters and/or 14651format effectors (blank lines) 14652 14653@item 14654the average number of code lines in subprogram bodies, task bodies, entry 14655bodies and statement sequences in package bodies (this metric is only computed 14656across the whole set of the analyzed units) 14657 14658@end itemize 14659 14660@noindent 14661@command{gnatmetric} sums the values of the line metrics for all the 14662files being processed and then generates the cumulative results. The tool 14663also computes for all the files being processed the average number of code 14664lines in bodies. 14665 14666You can use the following switches to select the specific line metrics 14667to be computed and reported. 14668 14669@table @option 14670@cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric}) 14671 14672@ifclear vms 14673@cindex @option{--no-lines@var{x}} 14674@end ifclear 14675 14676@item ^--lines-all^/LINE_COUNT_METRICS=ALL^ 14677Report all the line metrics 14678 14679@item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^ 14680Do not report any of line metrics 14681 14682@item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^ 14683Report the number of all lines 14684 14685@item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^ 14686Do not report the number of all lines 14687 14688@item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^ 14689Report the number of code lines 14690 14691@item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^ 14692Do not report the number of code lines 14693 14694@item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^ 14695Report the number of comment lines 14696 14697@item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^ 14698Do not report the number of comment lines 14699 14700@item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^ 14701Report the number of code lines containing 14702end-of-line comments 14703 14704@item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^ 14705Do not report the number of code lines containing 14706end-of-line comments 14707 14708@item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^ 14709Report the comment percentage in the program text 14710 14711@item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^ 14712Do not report the comment percentage in the program text 14713 14714@item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^ 14715Report the number of blank lines 14716 14717@item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^ 14718Do not report the number of blank lines 14719 14720@item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^ 14721Report the average number of code lines in subprogram bodies, task bodies, 14722entry bodies and statement sequences in package bodies. The metric is computed 14723and reported for the whole set of processed Ada sources only. 14724 14725@item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^ 14726Do not report the average number of code lines in subprogram bodies, 14727task bodies, entry bodies and statement sequences in package bodies. 14728 14729@end table 14730 14731@node Syntax Metrics Control 14732@subsubsection Syntax Metrics Control 14733@cindex Syntax metrics control in @command{gnatmetric} 14734 14735@noindent 14736@command{gnatmetric} computes various syntactic metrics for the 14737outermost unit and for each eligible local unit: 14738 14739@table @emph 14740@item LSLOC (``Logical Source Lines Of Code'') 14741The total number of declarations and the total number of statements. Note 14742that the definition of declarations is the one given in the reference 14743manual: 14744 14745@noindent 14746``Each of the following is defined to be a declaration: any basic_declaration; 14747an enumeration_literal_specification; a discriminant_specification; 14748a component_declaration; a loop_parameter_specification; a 14749parameter_specification; a subprogram_body; an entry_declaration; 14750an entry_index_specification; a choice_parameter_specification; 14751a generic_formal_parameter_declaration.'' 14752 14753This means for example that each enumeration literal adds one to the count, 14754as well as each subprogram parameter. 14755 14756Thus the results from this metric will be significantly greater than might 14757be expected from a naive view of counting semicolons. 14758 14759@item Maximal static nesting level of inner program units 14760According to 14761@cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a 14762package, a task unit, a protected unit, a 14763protected entry, a generic unit, or an explicitly declared subprogram other 14764than an enumeration literal.'' 14765 14766@item Maximal nesting level of composite syntactic constructs 14767This corresponds to the notion of the 14768maximum nesting level in the GNAT built-in style checks 14769(@pxref{Style Checking}) 14770@end table 14771 14772@noindent 14773For the outermost unit in the file, @command{gnatmetric} additionally computes 14774the following metrics: 14775 14776@table @emph 14777@item Public subprograms 14778This metric is computed for package specs. It is the 14779number of subprograms and generic subprograms declared in the visible 14780part (including the visible part of nested packages, protected objects, and 14781protected types). 14782 14783@item All subprograms 14784This metric is computed for bodies and subunits. The 14785metric is equal to a total number of subprogram bodies in the compilation 14786unit. 14787Neither generic instantiations nor renamings-as-a-body nor body stubs 14788are counted. Any subprogram body is counted, independently of its nesting 14789level and enclosing constructs. Generic bodies and bodies of protected 14790subprograms are counted in the same way as ``usual'' subprogram bodies. 14791 14792@item Public types 14793This metric is computed for package specs and 14794generic package declarations. It is the total number of types 14795that can be referenced from outside this compilation unit, plus the 14796number of types from all the visible parts of all the visible generic 14797packages. Generic formal types are not counted. Only types, not subtypes, 14798are included. 14799 14800@noindent 14801Along with the total number of public types, the following 14802types are counted and reported separately: 14803 14804@itemize @bullet 14805@item 14806Abstract types 14807 14808@item 14809Root tagged types (abstract, non-abstract, private, non-private). Type 14810extensions are @emph{not} counted 14811 14812@item 14813Private types (including private extensions) 14814 14815@item 14816Task types 14817 14818@item 14819Protected types 14820 14821@end itemize 14822 14823@item All types 14824This metric is computed for any compilation unit. It is equal to the total 14825number of the declarations of different types given in the compilation unit. 14826The private and the corresponding full type declaration are counted as one 14827type declaration. Incomplete type declarations and generic formal types 14828are not counted. 14829No distinction is made among different kinds of types (abstract, 14830private etc.); the total number of types is computed and reported. 14831 14832@end table 14833 14834@noindent 14835By default, all the syntax metrics are computed and reported. You can use the 14836following switches to select specific syntax metrics. 14837 14838@table @option 14839 14840@cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric}) 14841 14842@ifclear vms 14843@cindex @option{--no-syntax@var{x}} (@command{gnatmetric}) 14844@end ifclear 14845 14846@item ^--syntax-all^/SYNTAX_METRICS=ALL^ 14847Report all the syntax metrics 14848 14849@item ^--no-syntax-all^/SYNTAX_METRICS=NONE^ 14850Do not report any of syntax metrics 14851 14852@item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^ 14853Report the total number of declarations 14854 14855@item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^ 14856Do not report the total number of declarations 14857 14858@item ^--statements^/SYNTAX_METRICS=STATEMENTS^ 14859Report the total number of statements 14860 14861@item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^ 14862Do not report the total number of statements 14863 14864@item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^ 14865Report the number of public subprograms in a compilation unit 14866 14867@item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^ 14868Do not report the number of public subprograms in a compilation unit 14869 14870@item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^ 14871Report the number of all the subprograms in a compilation unit 14872 14873@item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^ 14874Do not report the number of all the subprograms in a compilation unit 14875 14876@item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^ 14877Report the number of public types in a compilation unit 14878 14879@item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^ 14880Do not report the number of public types in a compilation unit 14881 14882@item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^ 14883Report the number of all the types in a compilation unit 14884 14885@item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^ 14886Do not report the number of all the types in a compilation unit 14887 14888@item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^ 14889Report the maximal program unit nesting level 14890 14891@item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^ 14892Do not report the maximal program unit nesting level 14893 14894@item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^ 14895Report the maximal construct nesting level 14896 14897@item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^ 14898Do not report the maximal construct nesting level 14899 14900@end table 14901 14902@node Complexity Metrics Control 14903@subsubsection Complexity Metrics Control 14904@cindex Complexity metrics control in @command{gnatmetric} 14905 14906@noindent 14907For a program unit that is an executable body (a subprogram body (including 14908generic bodies), task body, entry body or a package body containing 14909its own statement sequence) @command{gnatmetric} computes the following 14910complexity metrics: 14911 14912@itemize @bullet 14913@item 14914McCabe cyclomatic complexity; 14915 14916@item 14917McCabe essential complexity; 14918 14919@item 14920maximal loop nesting level; 14921 14922@item 14923extra exit points (for subprograms); 14924@end itemize 14925 14926@noindent 14927The McCabe cyclomatic complexity metric is defined 14928in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} 14929 14930According to McCabe, both control statements and short-circuit control forms 14931should be taken into account when computing cyclomatic complexity. 14932For Ada 2012 we have also take into account conditional expressions 14933and quantified expressions. For each body, we compute three metric values: 14934 14935@itemize @bullet 14936@item 14937the complexity introduced by control 14938statements only, without taking into account short-circuit forms, 14939 14940@item 14941the complexity introduced by short-circuit control forms only, and 14942 14943@item 14944the total 14945cyclomatic complexity, which is the sum of these two values. 14946@end itemize 14947 14948@noindent 14949 14950The cyclomatic complexity is also computed for Ada 2012 expression functions. 14951An expression function cannot have statements as its components, so only one 14952metric value is computed as a cyclomatic complexity of an expression function. 14953 14954The origin of cyclomatic complexity metric is the need to estimate the number 14955of independent paths in the control flow graph that in turn gives the number 14956of tests needed to satisfy paths coverage testing completeness criterion. 14957Considered from the testing point of view, a static Ada @code{loop} (that is, 14958the @code{loop} statement having static subtype in loop parameter 14959specification) does not add to cyclomatic complexity. By providing 14960@option{^--no-static-loop^NO_STATIC_LOOP^} option a user 14961may specify that such loops should not be counted when computing the 14962cyclomatic complexity metric 14963 14964The Ada essential complexity metric is a McCabe cyclomatic complexity metric 14965counted for the code that is reduced by excluding all the pure structural Ada 14966control statements. An compound statement is considered as a non-structural 14967if it contains a @code{raise} or @code{return} statement as it subcomponent, 14968or if it contains a @code{goto} statement that transfers the control outside 14969the operator. A selective accept statement with @code{terminate} alternative 14970is considered as non-structural statement. When computing this metric, 14971@code{exit} statements are treated in the same way as @code{goto} 14972statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified. 14973 14974The Ada essential complexity metric defined here is intended to quantify 14975the extent to which the software is unstructured. It is adapted from 14976the McCabe essential complexity metric defined in 14977@url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more 14978suitable for typical Ada usage. For example, short circuit forms 14979are not penalized as unstructured in the Ada essential complexity metric. 14980 14981When computing cyclomatic and essential complexity, @command{gnatmetric} skips 14982the code in the exception handlers and in all the nested program units. The 14983code of assertions and predicates (that is, subprogram preconditions and 14984postconditions, subtype predicates and type invariants) is also skipped. 14985 14986By default, all the complexity metrics are computed and reported. 14987For more fine-grained control you can use 14988the following switches: 14989 14990@table @option 14991@cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric}) 14992 14993@ifclear vms 14994@cindex @option{--no-complexity@var{x}} 14995@end ifclear 14996 14997@item ^--complexity-all^/COMPLEXITY_METRICS=ALL^ 14998Report all the complexity metrics 14999 15000@item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^ 15001Do not report any of complexity metrics 15002 15003@item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^ 15004Report the McCabe Cyclomatic Complexity 15005 15006@item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^ 15007Do not report the McCabe Cyclomatic Complexity 15008 15009@item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^ 15010Report the Essential Complexity 15011 15012@item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^ 15013Do not report the Essential Complexity 15014 15015@item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^ 15016Report maximal loop nesting level 15017 15018@item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^ 15019Do not report maximal loop nesting level 15020 15021@item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^ 15022Report the average McCabe Cyclomatic Complexity for all the subprogram bodies, 15023task bodies, entry bodies and statement sequences in package bodies. 15024The metric is computed and reported for whole set of processed Ada sources 15025only. 15026 15027@item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^ 15028Do not report the average McCabe Cyclomatic Complexity for all the subprogram 15029bodies, task bodies, entry bodies and statement sequences in package bodies 15030 15031@cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric}) 15032@item ^-ne^/NO_EXITS_AS_GOTOS^ 15033Do not consider @code{exit} statements as @code{goto}s when 15034computing Essential Complexity 15035 15036@cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric}) 15037@item ^--no-static-loop^/NO_STATIC_LOOP^ 15038Do not consider static loops when computing cyclomatic complexity 15039 15040@item ^--extra-exit-points^/EXTRA_EXIT_POINTS^ 15041Report the extra exit points for subprogram bodies. As an exit point, this 15042metric counts @code{return} statements and raise statements in case when the 15043raised exception is not handled in the same body. In case of a function this 15044metric subtracts 1 from the number of exit points, because a function body 15045must contain at least one @code{return} statement. 15046 15047@item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^ 15048Do not report the extra exit points for subprogram bodies 15049@end table 15050 15051 15052@node Coupling Metrics Control 15053@subsubsection Coupling Metrics Control 15054@cindex Coupling metrics control in @command{gnatmetric} 15055 15056@noindent 15057@cindex Coupling metrics (in in @command{gnatmetric}) 15058Coupling metrics measure the dependencies between a given entity and other 15059entities the program consists of. The goal of these metrics is to estimate the 15060stability of the whole program considered as the collection of entities 15061(modules, classes etc.). 15062 15063Gnatmetric computes the following coupling metrics: 15064 15065@itemize @bullet 15066 15067@item 15068@emph{object-oriented coupling} - for classes in traditional object-oriented 15069sense; 15070 15071@item 15072@emph{unit coupling} - for all the program units making up a program; 15073 15074@item 15075@emph{control coupling} - this metric counts dependencies between a unit and 15076only those units that define subprograms; 15077@end itemize 15078 15079@noindent 15080Two kinds of coupling metrics are computed: 15081 15082@table @asis 15083@item fan-out coupling (efferent coupling) 15084@cindex fan-out coupling 15085@cindex efferent coupling 15086the number of entities the given entity depends upon. It 15087estimates in what extent the given entity depends on the changes in 15088``external world'' 15089 15090@item fan-in coupling (afferent coupling) 15091@cindex fan-in coupling 15092@cindex afferent coupling 15093the number of entities that depend on a given entity. 15094It estimates in what extent the ``external world'' depends on the changes in a 15095given entity 15096@end table 15097 15098@noindent 15099 15100Object-oriented coupling metrics are metrics that measure the dependencies 15101between a given class (or a group of classes) and the other classes in the 15102program. In this subsection the term ``class'' is used in its traditional 15103object-oriented programming sense (an instantiable module that contains data 15104and/or method members). A @emph{category} (of classes) is a group of closely 15105related classes that are reused and/or modified together. 15106 15107A class @code{K}'s fan-out coupling is the number of classes 15108that @code{K} depends upon. 15109A category's fan-out coupling is the number of classes outside the 15110category that the classes inside the category depend upon. 15111 15112A class @code{K}'s fan-in coupling is the number of classes 15113that depend upon @code{K}. 15114A category's fan-in coupling is the number of classes outside the 15115category that depend on classes belonging to the category. 15116 15117Ada's implementation of the object-oriented paradigm does not use the 15118traditional class notion, so the definition of the coupling 15119metrics for Ada maps the class and class category notions 15120onto Ada constructs. 15121 15122For the coupling metrics, several kinds of modules -- a library package, 15123a library generic package, and a library generic package instantiation -- 15124that define a tagged type or an interface type are 15125considered to be a class. A category consists of a library package (or 15126a library generic package) that defines a tagged or an interface type, 15127together with all its descendant (generic) packages that define tagged 15128or interface types. That is a 15129category is an Ada hierarchy of library-level program units. So class coupling 15130in case of Ada is called as tagged coupling, and category coupling - as 15131hierarchy coupling. 15132 15133For any package counted as a class, its body and subunits (if any) are 15134considered together with its spec when counting the dependencies, and coupling 15135metrics are reported for spec units only. For dependencies between classes, 15136the Ada semantic dependencies are considered. For object-oriented coupling 15137metrics, only dependencies on units that are considered as classes, are 15138considered. 15139 15140For unit and control coupling also not compilation units but program units are 15141counted. That is, for a package, its spec, its body and its subunits (if any) 15142are considered as making up one unit, and the dependencies that are counted 15143are the dependencies of all these compilation units collected together as 15144the dependencies as a (whole) unit. And metrics are reported for spec 15145compilation units only (or for a subprogram body unit in case if there is no 15146separate spec for the given subprogram). 15147 15148For unit coupling, dependencies between all kinds of program units are 15149considered. For control coupling, for each unit the dependencies of this unit 15150upon units that define subprograms are counted, so control fan-out coupling 15151is reported for all units, but control fan-in coupling - only for the units 15152that define subprograms. 15153 15154The following simple example illustrates the difference between unit coupling 15155and control coupling metrics: 15156 15157@smallexample @c ada 15158package Lib_1 is 15159 function F_1 (I : Integer) return Integer; 15160end Lib_1; 15161 15162package Lib_2 is 15163 type T_2 is new Integer; 15164end Lib_2; 15165 15166package body Lib_1 is 15167 function F_1 (I : Integer) return Integer is 15168 begin 15169 return I + 1; 15170 end F_1; 15171end Lib_1; 15172 15173with Lib_2; use Lib_2; 15174package Pack is 15175 Var : T_2; 15176 function Fun (I : Integer) return Integer; 15177end Pack; 15178 15179with Lib_1; use Lib_1; 15180package body Pack is 15181 function Fun (I : Integer) return Integer is 15182 begin 15183 return F_1 (I); 15184 end Fun; 15185end Pack; 15186@end smallexample 15187 15188@noindent 15189if we apply @command{gnatmetric} with @code{--coupling-all} option to these 15190units, the result will be: 15191 15192@smallexample 15193Coupling metrics: 15194================= 15195 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads) 15196 control fan-out coupling : 0 15197 control fan-in coupling : 1 15198 unit fan-out coupling : 0 15199 unit fan-in coupling : 1 15200 15201 Unit Pack (C:\customers\662\L406-007\pack.ads) 15202 control fan-out coupling : 1 15203 control fan-in coupling : 0 15204 unit fan-out coupling : 2 15205 unit fan-in coupling : 0 15206 15207 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads) 15208 control fan-out coupling : 0 15209 unit fan-out coupling : 0 15210 unit fan-in coupling : 1 15211@end smallexample 15212 15213@noindent 15214The result does not contain values for object-oriented 15215coupling because none of the argument unit contains a tagged type and 15216therefore none of these units can be treated as a class. 15217 15218@code{Pack} (considered as a program unit, that is spec+body) depends on two 15219units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling 15220equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as 15221well as control fan-in coupling. Only one of the units @code{Pack} depends 15222upon defines a subprogram, so its control fan-out coupling is 1. 15223 15224@code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does 15225not define a subprogram, so control fan-in metric cannot be applied to it, 15226and there is one unit that depends on it (@code{Pack}), so it has 15227unit fan-in coupling equals to 1. 15228 15229@code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram. 15230So it has control fan-in coupling equals to 1 (because there is a unit 15231depending on it). 15232 15233When computing coupling metrics, @command{gnatmetric} counts only 15234dependencies between units that are arguments of the @command{gnatmetric} 15235call. Coupling metrics are program-wide (or project-wide) metrics, so to 15236get a valid result, you should call @command{gnatmetric} for 15237the whole set of sources that make up your program. It can be done 15238by calling @command{gnatmetric} from the GNAT driver with @option{-U} 15239option (see @ref{The GNAT Driver and Project Files} for details). 15240 15241By default, all the coupling metrics are disabled. You can use the following 15242switches to specify the coupling metrics to be computed and reported: 15243 15244@table @option 15245 15246@ifclear vms 15247@cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric}) 15248@cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric}) 15249@cindex @option{--unit-coupling@var{x}} (@command{gnatmetric}) 15250@cindex @option{--control-coupling@var{x}} (@command{gnatmetric}) 15251@end ifclear 15252 15253@ifset vms 15254@cindex @option{/COUPLING_METRICS} (@command{gnatmetric}) 15255@end ifset 15256 15257@item ^--coupling-all^/COUPLING_METRICS=ALL^ 15258Report all the coupling metrics 15259 15260@item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^ 15261Report tagged (class) fan-out coupling 15262 15263@item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^ 15264Report tagged (class) fan-in coupling 15265 15266@item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^ 15267Report hierarchy (category) fan-out coupling 15268 15269@item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^ 15270Report hierarchy (category) fan-in coupling 15271 15272@item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^ 15273Report unit fan-out coupling 15274 15275@item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^ 15276Report unit fan-in coupling 15277 15278@item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^ 15279Report control fan-out coupling 15280 15281@item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^ 15282Report control fan-in coupling 15283@end table 15284 15285@node Other gnatmetric Switches 15286@subsection Other @code{gnatmetric} Switches 15287 15288@noindent 15289Additional @command{gnatmetric} switches are as follows: 15290 15291@table @option 15292@item ^-files @var{filename}^/FILES=@var{filename}^ 15293@cindex @option{^-files^/FILES^} (@code{gnatmetric}) 15294Take the argument source files from the specified file. This file should be an 15295ordinary text file containing file names separated by spaces or 15296line breaks. You can use this switch more than once in the same call to 15297@command{gnatmetric}. You also can combine this switch with 15298an explicit list of files. 15299 15300@item ^-v^/VERBOSE^ 15301@cindex @option{^-v^/VERBOSE^} (@code{gnatmetric}) 15302Verbose mode; 15303@command{gnatmetric} generates version information and then 15304a trace of sources being processed. 15305 15306@item ^-q^/QUIET^ 15307@cindex @option{^-q^/QUIET^} (@code{gnatmetric}) 15308Quiet mode. 15309@end table 15310 15311@node Generate project-wide metrics 15312@subsection Generate project-wide metrics 15313 15314In order to compute metrics on all units of a given project, you can use 15315the @command{gnat} driver along with the @option{-P} option: 15316@smallexample 15317 gnat metric -Pproj 15318@end smallexample 15319 15320@noindent 15321If the project @code{proj} depends upon other projects, you can compute 15322the metrics on the project closure using the @option{-U} option: 15323@smallexample 15324 gnat metric -Pproj -U 15325@end smallexample 15326 15327@noindent 15328Finally, if not all the units are relevant to a particular main 15329program in the project closure, you can generate metrics for the set 15330of units needed to create a given main program (unit closure) using 15331the @option{-U} option followed by the name of the main unit: 15332@smallexample 15333 gnat metric -Pproj -U main 15334@end smallexample 15335 15336 15337@c *********************************** 15338@node File Name Krunching Using gnatkr 15339@chapter File Name Krunching Using @code{gnatkr} 15340@findex gnatkr 15341 15342@noindent 15343This chapter discusses the method used by the compiler to shorten 15344the default file names chosen for Ada units so that they do not 15345exceed the maximum length permitted. It also describes the 15346@code{gnatkr} utility that can be used to determine the result of 15347applying this shortening. 15348@menu 15349* About gnatkr:: 15350* Using gnatkr:: 15351* Krunching Method:: 15352* Examples of gnatkr Usage:: 15353@end menu 15354 15355@node About gnatkr 15356@section About @code{gnatkr} 15357 15358@noindent 15359The default file naming rule in GNAT 15360is that the file name must be derived from 15361the unit name. The exact default rule is as follows: 15362@itemize @bullet 15363@item 15364Take the unit name and replace all dots by hyphens. 15365@item 15366If such a replacement occurs in the 15367second character position of a name, and the first character is 15368^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^ 15369then replace the dot by the character 15370^@samp{~} (tilde)^@samp{$} (dollar sign)^ 15371instead of a minus. 15372@end itemize 15373The reason for this exception is to avoid clashes 15374with the standard names for children of System, Ada, Interfaces, 15375and GNAT, which use the prefixes 15376^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^ 15377respectively. 15378 15379The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}} 15380switch of the compiler activates a ``krunching'' 15381circuit that limits file names to nn characters (where nn is a decimal 15382integer). For example, using OpenVMS, 15383where the maximum file name length is 1538439, the value of nn is usually set to 39, but if you want to generate 15385a set of files that would be usable if ported to a system with some 15386different maximum file length, then a different value can be specified. 15387The default value of 39 for OpenVMS need not be specified. 15388 15389The @code{gnatkr} utility can be used to determine the krunched name for 15390a given file, when krunched to a specified maximum length. 15391 15392@node Using gnatkr 15393@section Using @code{gnatkr} 15394 15395@noindent 15396The @code{gnatkr} command has the form 15397 15398@ifclear vms 15399@smallexample 15400@c $ gnatkr @var{name} @ovar{length} 15401@c Expanding @ovar macro inline (explanation in macro def comments) 15402$ gnatkr @var{name} @r{[}@var{length}@r{]} 15403@end smallexample 15404@end ifclear 15405 15406@ifset vms 15407@smallexample 15408$ gnatkr @var{name} /COUNT=nn 15409@end smallexample 15410@end ifset 15411 15412@noindent 15413@var{name} is the uncrunched file name, derived from the name of the unit 15414in the standard manner described in the previous section (i.e., in particular 15415all dots are replaced by hyphens). The file name may or may not have an 15416extension (defined as a suffix of the form period followed by arbitrary 15417characters other than period). If an extension is present then it will 15418be preserved in the output. For example, when krunching @file{hellofile.ads} 15419to eight characters, the result will be hellofil.ads. 15420 15421Note: for compatibility with previous versions of @code{gnatkr} dots may 15422appear in the name instead of hyphens, but the last dot will always be 15423taken as the start of an extension. So if @code{gnatkr} is given an argument 15424such as @file{Hello.World.adb} it will be treated exactly as if the first 15425period had been a hyphen, and for example krunching to eight characters 15426gives the result @file{hellworl.adb}. 15427 15428Note that the result is always all lower case (except on OpenVMS where it is 15429all upper case). Characters of the other case are folded as required. 15430 15431@var{length} represents the length of the krunched name. The default 15432when no argument is given is ^8^39^ characters. A length of zero stands for 15433unlimited, in other words do not chop except for system files where the 15434implied crunching length is always eight characters. 15435 15436@noindent 15437The output is the krunched name. The output has an extension only if the 15438original argument was a file name with an extension. 15439 15440@node Krunching Method 15441@section Krunching Method 15442 15443@noindent 15444The initial file name is determined by the name of the unit that the file 15445contains. The name is formed by taking the full expanded name of the 15446unit and replacing the separating dots with hyphens and 15447using ^lowercase^uppercase^ 15448for all letters, except that a hyphen in the second character position is 15449replaced by a ^tilde^dollar sign^ if the first character is 15450^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^. 15451The extension is @code{.ads} for a 15452spec and @code{.adb} for a body. 15453Krunching does not affect the extension, but the file name is shortened to 15454the specified length by following these rules: 15455 15456@itemize @bullet 15457@item 15458The name is divided into segments separated by hyphens, tildes or 15459underscores and all hyphens, tildes, and underscores are 15460eliminated. If this leaves the name short enough, we are done. 15461 15462@item 15463If the name is too long, the longest segment is located (left-most 15464if there are two of equal length), and shortened by dropping 15465its last character. This is repeated until the name is short enough. 15466 15467As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb} 15468to fit the name into 8 characters as required by some operating systems. 15469 15470@smallexample 15471our-strings-wide_fixed 22 15472our strings wide fixed 19 15473our string wide fixed 18 15474our strin wide fixed 17 15475our stri wide fixed 16 15476our stri wide fixe 15 15477our str wide fixe 14 15478our str wid fixe 13 15479our str wid fix 12 15480ou str wid fix 11 15481ou st wid fix 10 15482ou st wi fix 9 15483ou st wi fi 8 15484Final file name: oustwifi.adb 15485@end smallexample 15486 15487@item 15488The file names for all predefined units are always krunched to eight 15489characters. The krunching of these predefined units uses the following 15490special prefix replacements: 15491 15492@table @file 15493@item ada- 15494replaced by @file{^a^A^-} 15495 15496@item gnat- 15497replaced by @file{^g^G^-} 15498 15499@item interfaces- 15500replaced by @file{^i^I^-} 15501 15502@item system- 15503replaced by @file{^s^S^-} 15504@end table 15505 15506These system files have a hyphen in the second character position. That 15507is why normal user files replace such a character with a 15508^tilde^dollar sign^, to 15509avoid confusion with system file names. 15510 15511As an example of this special rule, consider 15512@*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows: 15513 15514@smallexample 15515ada-strings-wide_fixed 22 15516a- strings wide fixed 18 15517a- string wide fixed 17 15518a- strin wide fixed 16 15519a- stri wide fixed 15 15520a- stri wide fixe 14 15521a- str wide fixe 13 15522a- str wid fixe 12 15523a- str wid fix 11 15524a- st wid fix 10 15525a- st wi fix 9 15526a- st wi fi 8 15527Final file name: a-stwifi.adb 15528@end smallexample 15529@end itemize 15530 15531Of course no file shortening algorithm can guarantee uniqueness over all 15532possible unit names, and if file name krunching is used then it is your 15533responsibility to ensure that no name clashes occur. The utility 15534program @code{gnatkr} is supplied for conveniently determining the 15535krunched name of a file. 15536 15537@node Examples of gnatkr Usage 15538@section Examples of @code{gnatkr} Usage 15539 15540@smallexample 15541@iftex 15542@leftskip=0cm 15543@end iftex 15544@ifclear vms 15545$ gnatkr very_long_unit_name.ads --> velounna.ads 15546$ gnatkr grandparent-parent-child.ads --> grparchi.ads 15547$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads 15548$ gnatkr grandparent-parent-child --> grparchi 15549@end ifclear 15550$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads 15551$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads 15552@end smallexample 15553 15554@node Preprocessing Using gnatprep 15555@chapter Preprocessing Using @code{gnatprep} 15556@findex gnatprep 15557 15558@noindent 15559This chapter discusses how to use GNAT's @code{gnatprep} utility for simple 15560preprocessing. 15561Although designed for use with GNAT, @code{gnatprep} does not depend on any 15562special GNAT features. 15563For further discussion of conditional compilation in general, see 15564@ref{Conditional Compilation}. 15565 15566@menu 15567* Preprocessing Symbols:: 15568* Using gnatprep:: 15569* Switches for gnatprep:: 15570* Form of Definitions File:: 15571* Form of Input Text for gnatprep:: 15572@end menu 15573 15574@node Preprocessing Symbols 15575@section Preprocessing Symbols 15576 15577@noindent 15578Preprocessing symbols are defined in definition files and referred to in 15579sources to be preprocessed. A Preprocessing symbol is an identifier, following 15580normal Ada (case-insensitive) rules for its syntax, with the restriction that 15581all characters need to be in the ASCII set (no accented letters). 15582 15583@node Using gnatprep 15584@section Using @code{gnatprep} 15585 15586@noindent 15587To call @code{gnatprep} use 15588 15589@smallexample 15590@c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile} 15591@c Expanding @ovar macro inline (explanation in macro def comments) 15592$ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]} 15593@end smallexample 15594 15595@noindent 15596where 15597@table @var 15598@item switches 15599is an optional sequence of switches as described in the next section. 15600 15601@item infile 15602is the full name of the input file, which is an Ada source 15603file containing preprocessor directives. 15604 15605@item outfile 15606is the full name of the output file, which is an Ada source 15607in standard Ada form. When used with GNAT, this file name will 15608normally have an ads or adb suffix. 15609 15610@item deffile 15611is the full name of a text file containing definitions of 15612preprocessing symbols to be referenced by the preprocessor. This argument is 15613optional, and can be replaced by the use of the @option{-D} switch. 15614 15615@end table 15616 15617@node Switches for gnatprep 15618@section Switches for @code{gnatprep} 15619 15620@table @option 15621@c !sort! 15622 15623@item ^-b^/BLANK_LINES^ 15624@cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep}) 15625Causes both preprocessor lines and the lines deleted by 15626preprocessing to be replaced by blank lines in the output source file, 15627preserving line numbers in the output file. 15628 15629@item ^-c^/COMMENTS^ 15630@cindex @option{^-c^/COMMENTS^} (@command{gnatprep}) 15631Causes both preprocessor lines and the lines deleted 15632by preprocessing to be retained in the output source as comments marked 15633with the special string @code{"--! "}. This option will result in line numbers 15634being preserved in the output file. 15635 15636@item ^-C^/REPLACE_IN_COMMENTS^ 15637@cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep}) 15638Causes comments to be scanned. Normally comments are ignored by gnatprep. 15639If this option is specified, then comments are scanned and any $symbol 15640substitutions performed as in program text. This is particularly useful 15641when structured comments are used (e.g., when writing programs in the 15642SPARK dialect of Ada). Note that this switch is not available when 15643doing integrated preprocessing (it would be useless in this context 15644since comments are ignored by the compiler in any case). 15645 15646@item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^ 15647@cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep}) 15648Defines a new preprocessing symbol, associated with value. If no value is given 15649on the command line, then symbol is considered to be @code{True}. This switch 15650can be used in place of a definition file. 15651 15652@ifset vms 15653@item /REMOVE 15654@cindex @option{/REMOVE} (@command{gnatprep}) 15655This is the default setting which causes lines deleted by preprocessing 15656to be entirely removed from the output file. 15657@end ifset 15658 15659@item ^-r^/REFERENCE^ 15660@cindex @option{^-r^/REFERENCE^} (@command{gnatprep}) 15661Causes a @code{Source_Reference} pragma to be generated that 15662references the original input file, so that error messages will use 15663the file name of this original file. The use of this switch implies 15664that preprocessor lines are not to be removed from the file, so its 15665use will force @option{^-b^/BLANK_LINES^} mode if 15666@option{^-c^/COMMENTS^} 15667has not been specified explicitly. 15668 15669Note that if the file to be preprocessed contains multiple units, then 15670it will be necessary to @code{gnatchop} the output file from 15671@code{gnatprep}. If a @code{Source_Reference} pragma is present 15672in the preprocessed file, it will be respected by 15673@code{gnatchop ^-r^/REFERENCE^} 15674so that the final chopped files will correctly refer to the original 15675input source file for @code{gnatprep}. 15676 15677@item ^-s^/SYMBOLS^ 15678@cindex @option{^-s^/SYMBOLS^} (@command{gnatprep}) 15679Causes a sorted list of symbol names and values to be 15680listed on the standard output file. 15681 15682@item ^-u^/UNDEFINED^ 15683@cindex @option{^-u^/UNDEFINED^} (@command{gnatprep}) 15684Causes undefined symbols to be treated as having the value FALSE in the context 15685of a preprocessor test. In the absence of this option, an undefined symbol in 15686a @code{#if} or @code{#elsif} test will be treated as an error. 15687 15688@end table 15689 15690@ifclear vms 15691@noindent 15692Note: if neither @option{-b} nor @option{-c} is present, 15693then preprocessor lines and 15694deleted lines are completely removed from the output, unless -r is 15695specified, in which case -b is assumed. 15696@end ifclear 15697 15698@node Form of Definitions File 15699@section Form of Definitions File 15700 15701@noindent 15702The definitions file contains lines of the form 15703 15704@smallexample 15705symbol := value 15706@end smallexample 15707 15708@noindent 15709where symbol is a preprocessing symbol, and value is one of the following: 15710 15711@itemize @bullet 15712@item 15713Empty, corresponding to a null substitution 15714@item 15715A string literal using normal Ada syntax 15716@item 15717Any sequence of characters from the set 15718(letters, digits, period, underline). 15719@end itemize 15720 15721@noindent 15722Comment lines may also appear in the definitions file, starting with 15723the usual @code{--}, 15724and comments may be added to the definitions lines. 15725 15726@node Form of Input Text for gnatprep 15727@section Form of Input Text for @code{gnatprep} 15728 15729@noindent 15730The input text may contain preprocessor conditional inclusion lines, 15731as well as general symbol substitution sequences. 15732 15733The preprocessor conditional inclusion commands have the form 15734 15735@smallexample 15736@group 15737@cartouche 15738#if @i{expression} @r{[}then@r{]} 15739 lines 15740#elsif @i{expression} @r{[}then@r{]} 15741 lines 15742#elsif @i{expression} @r{[}then@r{]} 15743 lines 15744@dots{} 15745#else 15746 lines 15747#end if; 15748@end cartouche 15749@end group 15750@end smallexample 15751 15752@noindent 15753In this example, @i{expression} is defined by the following grammar: 15754@smallexample 15755@i{expression} ::= <symbol> 15756@i{expression} ::= <symbol> = "<value>" 15757@i{expression} ::= <symbol> = <symbol> 15758@i{expression} ::= <symbol> 'Defined 15759@i{expression} ::= not @i{expression} 15760@i{expression} ::= @i{expression} and @i{expression} 15761@i{expression} ::= @i{expression} or @i{expression} 15762@i{expression} ::= @i{expression} and then @i{expression} 15763@i{expression} ::= @i{expression} or else @i{expression} 15764@i{expression} ::= ( @i{expression} ) 15765@end smallexample 15766 15767The following restriction exists: it is not allowed to have "and" or "or" 15768following "not" in the same expression without parentheses. For example, this 15769is not allowed: 15770 15771@smallexample 15772 not X or Y 15773@end smallexample 15774 15775This should be one of the following: 15776 15777@smallexample 15778 (not X) or Y 15779 not (X or Y) 15780@end smallexample 15781 15782@noindent 15783For the first test (@i{expression} ::= <symbol>) the symbol must have 15784either the value true or false, that is to say the right-hand of the 15785symbol definition must be one of the (case-insensitive) literals 15786@code{True} or @code{False}. If the value is true, then the 15787corresponding lines are included, and if the value is false, they are 15788excluded. 15789 15790The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if 15791the symbol has been defined in the definition file or by a @option{-D} 15792switch on the command line. Otherwise, the test is false. 15793 15794The equality tests are case insensitive, as are all the preprocessor lines. 15795 15796If the symbol referenced is not defined in the symbol definitions file, 15797then the effect depends on whether or not switch @option{-u} 15798is specified. If so, then the symbol is treated as if it had the value 15799false and the test fails. If this switch is not specified, then 15800it is an error to reference an undefined symbol. It is also an error to 15801reference a symbol that is defined with a value other than @code{True} 15802or @code{False}. 15803 15804The use of the @code{not} operator inverts the sense of this logical test. 15805The @code{not} operator cannot be combined with the @code{or} or @code{and} 15806operators, without parentheses. For example, "if not X or Y then" is not 15807allowed, but "if (not X) or Y then" and "if not (X or Y) then" are. 15808 15809The @code{then} keyword is optional as shown 15810 15811The @code{#} must be the first non-blank character on a line, but 15812otherwise the format is free form. Spaces or tabs may appear between 15813the @code{#} and the keyword. The keywords and the symbols are case 15814insensitive as in normal Ada code. Comments may be used on a 15815preprocessor line, but other than that, no other tokens may appear on a 15816preprocessor line. Any number of @code{elsif} clauses can be present, 15817including none at all. The @code{else} is optional, as in Ada. 15818 15819The @code{#} marking the start of a preprocessor line must be the first 15820non-blank character on the line, i.e., it must be preceded only by 15821spaces or horizontal tabs. 15822 15823Symbol substitution outside of preprocessor lines is obtained by using 15824the sequence 15825 15826@smallexample 15827$symbol 15828@end smallexample 15829 15830@noindent 15831anywhere within a source line, except in a comment or within a 15832string literal. The identifier 15833following the @code{$} must match one of the symbols defined in the symbol 15834definition file, and the result is to substitute the value of the 15835symbol in place of @code{$symbol} in the output file. 15836 15837Note that although the substitution of strings within a string literal 15838is not possible, it is possible to have a symbol whose defined value is 15839a string literal. So instead of setting XYZ to @code{hello} and writing: 15840 15841@smallexample 15842Header : String := "$XYZ"; 15843@end smallexample 15844 15845@noindent 15846you should set XYZ to @code{"hello"} and write: 15847 15848@smallexample 15849Header : String := $XYZ; 15850@end smallexample 15851 15852@noindent 15853and then the substitution will occur as desired. 15854 15855@node The GNAT Library Browser gnatls 15856@chapter The GNAT Library Browser @code{gnatls} 15857@findex gnatls 15858@cindex Library browser 15859 15860@noindent 15861@code{gnatls} is a tool that outputs information about compiled 15862units. It gives the relationship between objects, unit names and source 15863files. It can also be used to check the source dependencies of a unit 15864as well as various characteristics. 15865 15866Note: to invoke @code{gnatls} with a project file, use the @code{gnat} 15867driver (see @ref{The GNAT Driver and Project Files}). 15868 15869@menu 15870* Running gnatls:: 15871* Switches for gnatls:: 15872* Examples of gnatls Usage:: 15873@end menu 15874 15875@node Running gnatls 15876@section Running @code{gnatls} 15877 15878@noindent 15879The @code{gnatls} command has the form 15880 15881@smallexample 15882$ gnatls switches @var{object_or_ali_file} 15883@end smallexample 15884 15885@noindent 15886The main argument is the list of object or @file{ali} files 15887(@pxref{The Ada Library Information Files}) 15888for which information is requested. 15889 15890In normal mode, without additional option, @code{gnatls} produces a 15891four-column listing. Each line represents information for a specific 15892object. The first column gives the full path of the object, the second 15893column gives the name of the principal unit in this object, the third 15894column gives the status of the source and the fourth column gives the 15895full path of the source representing this unit. 15896Here is a simple example of use: 15897 15898@smallexample 15899$ gnatls *.o 15900^./^[]^demo1.o demo1 DIF demo1.adb 15901^./^[]^demo2.o demo2 OK demo2.adb 15902^./^[]^hello.o h1 OK hello.adb 15903^./^[]^instr-child.o instr.child MOK instr-child.adb 15904^./^[]^instr.o instr OK instr.adb 15905^./^[]^tef.o tef DIF tef.adb 15906^./^[]^text_io_example.o text_io_example OK text_io_example.adb 15907^./^[]^tgef.o tgef DIF tgef.adb 15908@end smallexample 15909 15910@noindent 15911The first line can be interpreted as follows: the main unit which is 15912contained in 15913object file @file{demo1.o} is demo1, whose main source is in 15914@file{demo1.adb}. Furthermore, the version of the source used for the 15915compilation of demo1 has been modified (DIF). Each source file has a status 15916qualifier which can be: 15917 15918@table @code 15919@item OK (unchanged) 15920The version of the source file used for the compilation of the 15921specified unit corresponds exactly to the actual source file. 15922 15923@item MOK (slightly modified) 15924The version of the source file used for the compilation of the 15925specified unit differs from the actual source file but not enough to 15926require recompilation. If you use gnatmake with the qualifier 15927@option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked 15928MOK will not be recompiled. 15929 15930@item DIF (modified) 15931No version of the source found on the path corresponds to the source 15932used to build this object. 15933 15934@item ??? (file not found) 15935No source file was found for this unit. 15936 15937@item HID (hidden, unchanged version not first on PATH) 15938The version of the source that corresponds exactly to the source used 15939for compilation has been found on the path but it is hidden by another 15940version of the same source that has been modified. 15941 15942@end table 15943 15944@node Switches for gnatls 15945@section Switches for @code{gnatls} 15946 15947@noindent 15948@code{gnatls} recognizes the following switches: 15949 15950@table @option 15951@c !sort! 15952@cindex @option{--version} @command{gnatls} 15953Display Copyright and version, then exit disregarding all other options. 15954 15955@item --help 15956@cindex @option{--help} @command{gnatls} 15957If @option{--version} was not used, display usage, then exit disregarding 15958all other options. 15959 15960@item ^-a^/ALL_UNITS^ 15961@cindex @option{^-a^/ALL_UNITS^} (@code{gnatls}) 15962Consider all units, including those of the predefined Ada library. 15963Especially useful with @option{^-d^/DEPENDENCIES^}. 15964 15965@item ^-d^/DEPENDENCIES^ 15966@cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls}) 15967List sources from which specified units depend on. 15968 15969@item ^-h^/OUTPUT=OPTIONS^ 15970@cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls}) 15971Output the list of options. 15972 15973@item ^-o^/OUTPUT=OBJECTS^ 15974@cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls}) 15975Only output information about object files. 15976 15977@item ^-s^/OUTPUT=SOURCES^ 15978@cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls}) 15979Only output information about source files. 15980 15981@item ^-u^/OUTPUT=UNITS^ 15982@cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls}) 15983Only output information about compilation units. 15984 15985@item ^-files^/FILES^=@var{file} 15986@cindex @option{^-files^/FILES^} (@code{gnatls}) 15987Take as arguments the files listed in text file @var{file}. 15988Text file @var{file} may contain empty lines that are ignored. 15989Each nonempty line should contain the name of an existing file. 15990Several such switches may be specified simultaneously. 15991 15992@item ^-aO^/OBJECT_SEARCH=^@var{dir} 15993@itemx ^-aI^/SOURCE_SEARCH=^@var{dir} 15994@itemx ^-I^/SEARCH=^@var{dir} 15995@itemx ^-I-^/NOCURRENT_DIRECTORY^ 15996@itemx -nostdinc 15997@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls}) 15998@cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls}) 15999@cindex @option{^-I^/SEARCH^} (@code{gnatls}) 16000@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls}) 16001Source path manipulation. Same meaning as the equivalent @command{gnatmake} 16002flags (@pxref{Switches for gnatmake}). 16003 16004@item --RTS=@var{rts-path} 16005@cindex @option{--RTS} (@code{gnatls}) 16006Specifies the default location of the runtime library. Same meaning as the 16007equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}). 16008 16009@item ^-v^/OUTPUT=VERBOSE^ 16010@cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls}) 16011Verbose mode. Output the complete source, object and project paths. Do not use 16012the default column layout but instead use long format giving as much as 16013information possible on each requested units, including special 16014characteristics such as: 16015 16016@table @code 16017@item Preelaborable 16018The unit is preelaborable in the Ada sense. 16019 16020@item No_Elab_Code 16021No elaboration code has been produced by the compiler for this unit. 16022 16023@item Pure 16024The unit is pure in the Ada sense. 16025 16026@item Elaborate_Body 16027The unit contains a pragma Elaborate_Body. 16028 16029@item Remote_Types 16030The unit contains a pragma Remote_Types. 16031 16032@item Shared_Passive 16033The unit contains a pragma Shared_Passive. 16034 16035@item Predefined 16036This unit is part of the predefined environment and cannot be modified 16037by the user. 16038 16039@item Remote_Call_Interface 16040The unit contains a pragma Remote_Call_Interface. 16041 16042@end table 16043 16044@end table 16045 16046@node Examples of gnatls Usage 16047@section Example of @code{gnatls} Usage 16048@ifclear vms 16049 16050@noindent 16051Example of using the verbose switch. Note how the source and 16052object paths are affected by the -I switch. 16053 16054@smallexample 16055$ gnatls -v -I.. demo1.o 16056 16057GNATLS 5.03w (20041123-34) 16058Copyright 1997-2004 Free Software Foundation, Inc. 16059 16060Source Search Path: 16061 <Current_Directory> 16062 ../ 16063 /home/comar/local/adainclude/ 16064 16065Object Search Path: 16066 <Current_Directory> 16067 ../ 16068 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/ 16069 16070Project Search Path: 16071 <Current_Directory> 16072 /home/comar/local/lib/gnat/ 16073 16074./demo1.o 16075 Unit => 16076 Name => demo1 16077 Kind => subprogram body 16078 Flags => No_Elab_Code 16079 Source => demo1.adb modified 16080@end smallexample 16081 16082@noindent 16083The following is an example of use of the dependency list. 16084Note the use of the -s switch 16085which gives a straight list of source files. This can be useful for 16086building specialized scripts. 16087 16088@smallexample 16089$ gnatls -d demo2.o 16090./demo2.o demo2 OK demo2.adb 16091 OK gen_list.ads 16092 OK gen_list.adb 16093 OK instr.ads 16094 OK instr-child.ads 16095 16096$ gnatls -d -s -a demo1.o 16097demo1.adb 16098/home/comar/local/adainclude/ada.ads 16099/home/comar/local/adainclude/a-finali.ads 16100/home/comar/local/adainclude/a-filico.ads 16101/home/comar/local/adainclude/a-stream.ads 16102/home/comar/local/adainclude/a-tags.ads 16103gen_list.ads 16104gen_list.adb 16105/home/comar/local/adainclude/gnat.ads 16106/home/comar/local/adainclude/g-io.ads 16107instr.ads 16108/home/comar/local/adainclude/system.ads 16109/home/comar/local/adainclude/s-exctab.ads 16110/home/comar/local/adainclude/s-finimp.ads 16111/home/comar/local/adainclude/s-finroo.ads 16112/home/comar/local/adainclude/s-secsta.ads 16113/home/comar/local/adainclude/s-stalib.ads 16114/home/comar/local/adainclude/s-stoele.ads 16115/home/comar/local/adainclude/s-stratt.ads 16116/home/comar/local/adainclude/s-tasoli.ads 16117/home/comar/local/adainclude/s-unstyp.ads 16118/home/comar/local/adainclude/unchconv.ads 16119@end smallexample 16120@end ifclear 16121 16122@ifset vms 16123@smallexample 16124GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB 16125 16126GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads 16127GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads 16128GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads 16129GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads 16130GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads 16131demo1.adb 16132gen_list.ads 16133gen_list.adb 16134GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads 16135GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads 16136instr.ads 16137GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads 16138GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads 16139GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads 16140GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads 16141GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads 16142GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads 16143GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads 16144GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads 16145GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads 16146GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads 16147GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads 16148@end smallexample 16149@end ifset 16150 16151@node Cleaning Up Using gnatclean 16152@chapter Cleaning Up Using @code{gnatclean} 16153@findex gnatclean 16154@cindex Cleaning tool 16155 16156@noindent 16157@code{gnatclean} is a tool that allows the deletion of files produced by the 16158compiler, binder and linker, including ALI files, object files, tree files, 16159expanded source files, library files, interface copy source files, binder 16160generated files and executable files. 16161 16162@menu 16163* Running gnatclean:: 16164* Switches for gnatclean:: 16165@c * Examples of gnatclean Usage:: 16166@end menu 16167 16168@node Running gnatclean 16169@section Running @code{gnatclean} 16170 16171@noindent 16172The @code{gnatclean} command has the form: 16173 16174@smallexample 16175$ gnatclean switches @var{names} 16176@end smallexample 16177 16178@noindent 16179@var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and 16180@code{^adb^ADB^} may be omitted. If a project file is specified using switch 16181@code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted. 16182 16183@noindent 16184In normal mode, @code{gnatclean} delete the files produced by the compiler and, 16185if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and 16186the linker. In informative-only mode, specified by switch 16187@code{^-n^/NODELETE^}, the list of files that would have been deleted in 16188normal mode is listed, but no file is actually deleted. 16189 16190@node Switches for gnatclean 16191@section Switches for @code{gnatclean} 16192 16193@noindent 16194@code{gnatclean} recognizes the following switches: 16195 16196@table @option 16197@c !sort! 16198@cindex @option{--version} @command{gnatclean} 16199Display Copyright and version, then exit disregarding all other options. 16200 16201@item --help 16202@cindex @option{--help} @command{gnatclean} 16203If @option{--version} was not used, display usage, then exit disregarding 16204all other options. 16205 16206@item ^--subdirs^/SUBDIRS^=subdir 16207Actual object directory of each project file is the subdirectory subdir of the 16208object directory specified or defaulted in the project file. 16209 16210@item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^ 16211By default, shared library projects are not allowed to import static library 16212projects. When this switch is used on the command line, this restriction is 16213relaxed. 16214 16215@item ^-c^/COMPILER_FILES_ONLY^ 16216@cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean}) 16217Only attempt to delete the files produced by the compiler, not those produced 16218by the binder or the linker. The files that are not to be deleted are library 16219files, interface copy files, binder generated files and executable files. 16220 16221@item ^-D ^/DIRECTORY_OBJECTS=^@var{dir} 16222@cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean}) 16223Indicate that ALI and object files should normally be found in directory 16224@var{dir}. 16225 16226@item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^ 16227@cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean}) 16228When using project files, if some errors or warnings are detected during 16229parsing and verbose mode is not in effect (no use of switch 16230^-v^/VERBOSE^), then error lines start with the full path name of the project 16231file, rather than its simple file name. 16232 16233@item ^-h^/HELP^ 16234@cindex @option{^-h^/HELP^} (@code{gnatclean}) 16235Output a message explaining the usage of @code{^gnatclean^gnatclean^}. 16236 16237@item ^-n^/NODELETE^ 16238@cindex @option{^-n^/NODELETE^} (@code{gnatclean}) 16239Informative-only mode. Do not delete any files. Output the list of the files 16240that would have been deleted if this switch was not specified. 16241 16242@item ^-P^/PROJECT_FILE=^@var{project} 16243@cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean}) 16244Use project file @var{project}. Only one such switch can be used. 16245When cleaning a project file, the files produced by the compilation of the 16246immediate sources or inherited sources of the project files are to be 16247deleted. This is not depending on the presence or not of executable names 16248on the command line. 16249 16250@item ^-q^/QUIET^ 16251@cindex @option{^-q^/QUIET^} (@code{gnatclean}) 16252Quiet output. If there are no errors, do not output anything, except in 16253verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode 16254(switch ^-n^/NODELETE^). 16255 16256@item ^-r^/RECURSIVE^ 16257@cindex @option{^-r^/RECURSIVE^} (@code{gnatclean}) 16258When a project file is specified (using switch ^-P^/PROJECT_FILE=^), 16259clean all imported and extended project files, recursively. If this switch 16260is not specified, only the files related to the main project file are to be 16261deleted. This switch has no effect if no project file is specified. 16262 16263@item ^-v^/VERBOSE^ 16264@cindex @option{^-v^/VERBOSE^} (@code{gnatclean}) 16265Verbose mode. 16266 16267@item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x} 16268@cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean}) 16269Indicates the verbosity of the parsing of GNAT project files. 16270@xref{Switches Related to Project Files}. 16271 16272@item ^-X^/EXTERNAL_REFERENCE=^@var{name=value} 16273@cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean}) 16274Indicates that external variable @var{name} has the value @var{value}. 16275The Project Manager will use this value for occurrences of 16276@code{external(name)} when parsing the project file. 16277@xref{Switches Related to Project Files}. 16278 16279@item ^-aO^/OBJECT_SEARCH=^@var{dir} 16280@cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean}) 16281When searching for ALI and object files, look in directory 16282@var{dir}. 16283 16284@item ^-I^/SEARCH=^@var{dir} 16285@cindex @option{^-I^/SEARCH^} (@code{gnatclean}) 16286Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}. 16287 16288@item ^-I-^/NOCURRENT_DIRECTORY^ 16289@cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean}) 16290@cindex Source files, suppressing search 16291Do not look for ALI or object files in the directory 16292where @code{gnatclean} was invoked. 16293 16294@end table 16295 16296@c @node Examples of gnatclean Usage 16297@c @section Examples of @code{gnatclean} Usage 16298 16299@ifclear vms 16300@node GNAT and Libraries 16301@chapter GNAT and Libraries 16302@cindex Library, building, installing, using 16303 16304@noindent 16305This chapter describes how to build and use libraries with GNAT, and also shows 16306how to recompile the GNAT run-time library. You should be familiar with the 16307Project Manager facility (@pxref{GNAT Project Manager}) before reading this 16308chapter. 16309 16310@menu 16311* Introduction to Libraries in GNAT:: 16312* General Ada Libraries:: 16313* Stand-alone Ada Libraries:: 16314* Rebuilding the GNAT Run-Time Library:: 16315@end menu 16316 16317@node Introduction to Libraries in GNAT 16318@section Introduction to Libraries in GNAT 16319 16320@noindent 16321A library is, conceptually, a collection of objects which does not have its 16322own main thread of execution, but rather provides certain services to the 16323applications that use it. A library can be either statically linked with the 16324application, in which case its code is directly included in the application, 16325or, on platforms that support it, be dynamically linked, in which case 16326its code is shared by all applications making use of this library. 16327 16328GNAT supports both types of libraries. 16329In the static case, the compiled code can be provided in different ways. The 16330simplest approach is to provide directly the set of objects resulting from 16331compilation of the library source files. Alternatively, you can group the 16332objects into an archive using whatever commands are provided by the operating 16333system. For the latter case, the objects are grouped into a shared library. 16334 16335In the GNAT environment, a library has three types of components: 16336@itemize @bullet 16337@item 16338Source files. 16339@item 16340@file{ALI} files. 16341@xref{The Ada Library Information Files}. 16342@item 16343Object files, an archive or a shared library. 16344@end itemize 16345 16346@noindent 16347A GNAT library may expose all its source files, which is useful for 16348documentation purposes. Alternatively, it may expose only the units needed by 16349an external user to make use of the library. That is to say, the specs 16350reflecting the library services along with all the units needed to compile 16351those specs, which can include generic bodies or any body implementing an 16352inlined routine. In the case of @emph{stand-alone libraries} those exposed 16353units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}). 16354 16355All compilation units comprising an application, including those in a library, 16356need to be elaborated in an order partially defined by Ada's semantics. GNAT 16357computes the elaboration order from the @file{ALI} files and this is why they 16358constitute a mandatory part of GNAT libraries. 16359@emph{Stand-alone libraries} are the exception to this rule because a specific 16360library elaboration routine is produced independently of the application(s) 16361using the library. 16362 16363@node General Ada Libraries 16364@section General Ada Libraries 16365 16366@menu 16367* Building a library:: 16368* Installing a library:: 16369* Using a library:: 16370@end menu 16371 16372@node Building a library 16373@subsection Building a library 16374 16375@noindent 16376The easiest way to build a library is to use the Project Manager, 16377which supports a special type of project called a @emph{Library Project} 16378(@pxref{Library Projects}). 16379 16380A project is considered a library project, when two project-level attributes 16381are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to 16382control different aspects of library configuration, additional optional 16383project-level attributes can be specified: 16384@table @code 16385@item Library_Kind 16386This attribute controls whether the library is to be static or dynamic 16387 16388@item Library_Version 16389This attribute specifies the library version; this value is used 16390during dynamic linking of shared libraries to determine if the currently 16391installed versions of the binaries are compatible. 16392 16393@item Library_Options 16394@item Library_GCC 16395These attributes specify additional low-level options to be used during 16396library generation, and redefine the actual application used to generate 16397library. 16398@end table 16399 16400@noindent 16401The GNAT Project Manager takes full care of the library maintenance task, 16402including recompilation of the source files for which objects do not exist 16403or are not up to date, assembly of the library archive, and installation of 16404the library (i.e., copying associated source, object and @file{ALI} files 16405to the specified location). 16406 16407Here is a simple library project file: 16408@smallexample @c ada 16409project My_Lib is 16410 for Source_Dirs use ("src1", "src2"); 16411 for Object_Dir use "obj"; 16412 for Library_Name use "mylib"; 16413 for Library_Dir use "lib"; 16414 for Library_Kind use "dynamic"; 16415end My_lib; 16416@end smallexample 16417 16418@noindent 16419and the compilation command to build and install the library: 16420 16421@smallexample @c ada 16422 $ gnatmake -Pmy_lib 16423@end smallexample 16424 16425@noindent 16426It is not entirely trivial to perform manually all the steps required to 16427produce a library. We recommend that you use the GNAT Project Manager 16428for this task. In special cases where this is not desired, the necessary 16429steps are discussed below. 16430 16431There are various possibilities for compiling the units that make up the 16432library: for example with a Makefile (@pxref{Using the GNU make Utility}) or 16433with a conventional script. For simple libraries, it is also possible to create 16434a dummy main program which depends upon all the packages that comprise the 16435interface of the library. This dummy main program can then be given to 16436@command{gnatmake}, which will ensure that all necessary objects are built. 16437 16438After this task is accomplished, you should follow the standard procedure 16439of the underlying operating system to produce the static or shared library. 16440 16441Here is an example of such a dummy program: 16442@smallexample @c ada 16443@group 16444with My_Lib.Service1; 16445with My_Lib.Service2; 16446with My_Lib.Service3; 16447procedure My_Lib_Dummy is 16448begin 16449 null; 16450end; 16451@end group 16452@end smallexample 16453 16454@noindent 16455Here are the generic commands that will build an archive or a shared library. 16456 16457@smallexample 16458# compiling the library 16459$ gnatmake -c my_lib_dummy.adb 16460 16461# we don't need the dummy object itself 16462$ rm my_lib_dummy.o my_lib_dummy.ali 16463 16464# create an archive with the remaining objects 16465$ ar rc libmy_lib.a *.o 16466# some systems may require "ranlib" to be run as well 16467 16468# or create a shared library 16469$ gcc -shared -o libmy_lib.so *.o 16470# some systems may require the code to have been compiled with -fPIC 16471 16472# remove the object files that are now in the library 16473$ rm *.o 16474 16475# Make the ALI files read-only so that gnatmake will not try to 16476# regenerate the objects that are in the library 16477$ chmod -w *.ali 16478@end smallexample 16479 16480@noindent 16481Please note that the library must have a name of the form @file{lib@var{xxx}.a} 16482or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to 16483be accessed by the directive @option{-l@var{xxx}} at link time. 16484 16485@node Installing a library 16486@subsection Installing a library 16487@cindex @code{ADA_PROJECT_PATH} 16488@cindex @code{GPR_PROJECT_PATH} 16489 16490@noindent 16491If you use project files, library installation is part of the library build 16492process (@pxref{Installing a library with project files}). 16493 16494When project files are not an option, it is also possible, but not recommended, 16495to install the library so that the sources needed to use the library are on the 16496Ada source path and the ALI files & libraries be on the Ada Object path (see 16497@ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system 16498administrator can place general-purpose libraries in the default compiler 16499paths, by specifying the libraries' location in the configuration files 16500@file{ada_source_path} and @file{ada_object_path}. These configuration files 16501must be located in the GNAT installation tree at the same place as the gcc spec 16502file. The location of the gcc spec file can be determined as follows: 16503@smallexample 16504$ gcc -v 16505@end smallexample 16506 16507@noindent 16508The configuration files mentioned above have a simple format: each line 16509must contain one unique directory name. 16510Those names are added to the corresponding path 16511in their order of appearance in the file. The names can be either absolute 16512or relative; in the latter case, they are relative to where theses files 16513are located. 16514 16515The files @file{ada_source_path} and @file{ada_object_path} might not be 16516present in a 16517GNAT installation, in which case, GNAT will look for its run-time library in 16518the directories @file{adainclude} (for the sources) and @file{adalib} (for the 16519objects and @file{ALI} files). When the files exist, the compiler does not 16520look in @file{adainclude} and @file{adalib}, and thus the 16521@file{ada_source_path} file 16522must contain the location for the GNAT run-time sources (which can simply 16523be @file{adainclude}). In the same way, the @file{ada_object_path} file must 16524contain the location for the GNAT run-time objects (which can simply 16525be @file{adalib}). 16526 16527You can also specify a new default path to the run-time library at compilation 16528time with the switch @option{--RTS=rts-path}. You can thus choose / change 16529the run-time library you want your program to be compiled with. This switch is 16530recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind}, 16531@command{gnatls}, @command{gnatfind} and @command{gnatxref}. 16532 16533It is possible to install a library before or after the standard GNAT 16534library, by reordering the lines in the configuration files. In general, a 16535library must be installed before the GNAT library if it redefines 16536any part of it. 16537 16538@node Using a library 16539@subsection Using a library 16540 16541@noindent Once again, the project facility greatly simplifies the use of 16542libraries. In this context, using a library is just a matter of adding a 16543@code{with} clause in the user project. For instance, to make use of the 16544library @code{My_Lib} shown in examples in earlier sections, you can 16545write: 16546 16547@smallexample @c projectfile 16548with "my_lib"; 16549project My_Proj is 16550 @dots{} 16551end My_Proj; 16552@end smallexample 16553 16554Even if you have a third-party, non-Ada library, you can still use GNAT's 16555Project Manager facility to provide a wrapper for it. For example, the 16556following project, when @code{with}ed by your main project, will link with the 16557third-party library @file{liba.a}: 16558 16559@smallexample @c projectfile 16560@group 16561project Liba is 16562 for Externally_Built use "true"; 16563 for Source_Files use (); 16564 for Library_Dir use "lib"; 16565 for Library_Name use "a"; 16566 for Library_Kind use "static"; 16567end Liba; 16568@end group 16569@end smallexample 16570This is an alternative to the use of @code{pragma Linker_Options}. It is 16571especially interesting in the context of systems with several interdependent 16572static libraries where finding a proper linker order is not easy and best be 16573left to the tools having visibility over project dependence information. 16574 16575@noindent 16576In order to use an Ada library manually, you need to make sure that this 16577library is on both your source and object path 16578(see @ref{Search Paths and the Run-Time Library (RTL)} 16579and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped 16580in an archive or a shared library, you need to specify the desired 16581library at link time. 16582 16583For example, you can use the library @file{mylib} installed in 16584@file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands: 16585 16586@smallexample 16587$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \ 16588 -largs -lmy_lib 16589@end smallexample 16590 16591@noindent 16592This can be expressed more simply: 16593@smallexample 16594$ gnatmake my_appl 16595@end smallexample 16596@noindent 16597when the following conditions are met: 16598@itemize @bullet 16599@item 16600@file{/dir/my_lib_src} has been added by the user to the environment 16601variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file 16602@file{ada_source_path} 16603@item 16604@file{/dir/my_lib_obj} has been added by the user to the environment 16605variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file 16606@file{ada_object_path} 16607@item 16608a pragma @code{Linker_Options} has been added to one of the sources. 16609For example: 16610 16611@smallexample @c ada 16612pragma Linker_Options ("-lmy_lib"); 16613@end smallexample 16614@end itemize 16615 16616@node Stand-alone Ada Libraries 16617@section Stand-alone Ada Libraries 16618@cindex Stand-alone library, building, using 16619 16620@menu 16621* Introduction to Stand-alone Libraries:: 16622* Building a Stand-alone Library:: 16623* Creating a Stand-alone Library to be used in a non-Ada context:: 16624* Restrictions in Stand-alone Libraries:: 16625@end menu 16626 16627@node Introduction to Stand-alone Libraries 16628@subsection Introduction to Stand-alone Libraries 16629 16630@noindent 16631A Stand-alone Library (abbreviated ``SAL'') is a library that contains the 16632necessary code to 16633elaborate the Ada units that are included in the library. In contrast with 16634an ordinary library, which consists of all sources, objects and @file{ALI} 16635files of the 16636library, a SAL may specify a restricted subset of compilation units 16637to serve as a library interface. In this case, the fully 16638self-sufficient set of files will normally consist of an objects 16639archive, the sources of interface units' specs, and the @file{ALI} 16640files of interface units. 16641If an interface spec contains a generic unit or an inlined subprogram, 16642the body's 16643source must also be provided; if the units that must be provided in the source 16644form depend on other units, the source and @file{ALI} files of those must 16645also be provided. 16646 16647The main purpose of a SAL is to minimize the recompilation overhead of client 16648applications when a new version of the library is installed. Specifically, 16649if the interface sources have not changed, client applications do not need to 16650be recompiled. If, furthermore, a SAL is provided in the shared form and its 16651version, controlled by @code{Library_Version} attribute, is not changed, 16652then the clients do not need to be relinked. 16653 16654SALs also allow the library providers to minimize the amount of library source 16655text exposed to the clients. Such ``information hiding'' might be useful or 16656necessary for various reasons. 16657 16658Stand-alone libraries are also well suited to be used in an executable whose 16659main routine is not written in Ada. 16660 16661@node Building a Stand-alone Library 16662@subsection Building a Stand-alone Library 16663 16664@noindent 16665GNAT's Project facility provides a simple way of building and installing 16666stand-alone libraries; see @ref{Stand-alone Library Projects}. 16667To be a Stand-alone Library Project, in addition to the two attributes 16668that make a project a Library Project (@code{Library_Name} and 16669@code{Library_Dir}; see @ref{Library Projects}), the attribute 16670@code{Library_Interface} must be defined. For example: 16671 16672@smallexample @c projectfile 16673@group 16674 for Library_Dir use "lib_dir"; 16675 for Library_Name use "dummy"; 16676 for Library_Interface use ("int1", "int1.child"); 16677@end group 16678@end smallexample 16679 16680@noindent 16681Attribute @code{Library_Interface} has a non-empty string list value, 16682each string in the list designating a unit contained in an immediate source 16683of the project file. 16684 16685When a Stand-alone Library is built, first the binder is invoked to build 16686a package whose name depends on the library name 16687(@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above). 16688This binder-generated package includes initialization and 16689finalization procedures whose 16690names depend on the library name (@code{dummyinit} and @code{dummyfinal} 16691in the example 16692above). The object corresponding to this package is included in the library. 16693 16694You must ensure timely (e.g., prior to any use of interfaces in the SAL) 16695calling of these procedures if a static SAL is built, or if a shared SAL 16696is built 16697with the project-level attribute @code{Library_Auto_Init} set to 16698@code{"false"}. 16699 16700For a Stand-Alone Library, only the @file{ALI} files of the Interface Units 16701(those that are listed in attribute @code{Library_Interface}) are copied to 16702the Library Directory. As a consequence, only the Interface Units may be 16703imported from Ada units outside of the library. If other units are imported, 16704the binding phase will fail. 16705 16706@noindent 16707It is also possible to build an encapsulated library where not only 16708the code to elaborate and finalize the library is embedded but also 16709ensuring that the library is linked only against static 16710libraries. So an encapsulated library only depends on system 16711libraries, all other code, including the GNAT runtime, is embedded. To 16712build an encapsulated library the attribute 16713@code{Library_Standalone} must be set to @code{encapsulated}: 16714 16715@smallexample @c projectfile 16716@group 16717 for Library_Dir use "lib_dir"; 16718 for Library_Name use "dummy"; 16719 for Library_Interface use ("int1", "int1.child"); 16720 for Library_Standalone use "encapsulated"; 16721@end group 16722@end smallexample 16723 16724@noindent 16725The default value for this attribute is @code{standard} in which case 16726a stand-alone library is built. 16727 16728The attribute @code{Library_Src_Dir} may be specified for a 16729Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a 16730single string value. Its value must be the path (absolute or relative to the 16731project directory) of an existing directory. This directory cannot be the 16732object directory or one of the source directories, but it can be the same as 16733the library directory. The sources of the Interface 16734Units of the library that are needed by an Ada client of the library will be 16735copied to the designated directory, called the Interface Copy directory. 16736These sources include the specs of the Interface Units, but they may also 16737include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always} 16738are used, or when there is a generic unit in the spec. Before the sources 16739are copied to the Interface Copy directory, an attempt is made to delete all 16740files in the Interface Copy directory. 16741 16742Building stand-alone libraries by hand is somewhat tedious, but for those 16743occasions when it is necessary here are the steps that you need to perform: 16744@itemize @bullet 16745@item 16746Compile all library sources. 16747 16748@item 16749Invoke the binder with the switch @option{-n} (No Ada main program), 16750with all the @file{ALI} files of the interfaces, and 16751with the switch @option{-L} to give specific names to the @code{init} 16752and @code{final} procedures. For example: 16753@smallexample 16754 gnatbind -n int1.ali int2.ali -Lsal1 16755@end smallexample 16756 16757@item 16758Compile the binder generated file: 16759@smallexample 16760 gcc -c b~int2.adb 16761@end smallexample 16762 16763@item 16764Link the dynamic library with all the necessary object files, 16765indicating to the linker the names of the @code{init} (and possibly 16766@code{final}) procedures for automatic initialization (and finalization). 16767The built library should be placed in a directory different from 16768the object directory. 16769 16770@item 16771Copy the @code{ALI} files of the interface to the library directory, 16772add in this copy an indication that it is an interface to a SAL 16773(i.e., add a word @option{SL} on the line in the @file{ALI} file that starts 16774with letter ``P'') and make the modified copy of the @file{ALI} file 16775read-only. 16776@end itemize 16777 16778@noindent 16779Using SALs is not different from using other libraries 16780(see @ref{Using a library}). 16781 16782@node Creating a Stand-alone Library to be used in a non-Ada context 16783@subsection Creating a Stand-alone Library to be used in a non-Ada context 16784 16785@noindent 16786It is easy to adapt the SAL build procedure discussed above for use of a SAL in 16787a non-Ada context. 16788 16789The only extra step required is to ensure that library interface subprograms 16790are compatible with the main program, by means of @code{pragma Export} 16791or @code{pragma Convention}. 16792 16793Here is an example of simple library interface for use with C main program: 16794 16795@smallexample @c ada 16796package My_Package is 16797 16798 procedure Do_Something; 16799 pragma Export (C, Do_Something, "do_something"); 16800 16801 procedure Do_Something_Else; 16802 pragma Export (C, Do_Something_Else, "do_something_else"); 16803 16804end My_Package; 16805@end smallexample 16806 16807@noindent 16808On the foreign language side, you must provide a ``foreign'' view of the 16809library interface; remember that it should contain elaboration routines in 16810addition to interface subprograms. 16811 16812The example below shows the content of @code{mylib_interface.h} (note 16813that there is no rule for the naming of this file, any name can be used) 16814@smallexample 16815/* the library elaboration procedure */ 16816extern void mylibinit (void); 16817 16818/* the library finalization procedure */ 16819extern void mylibfinal (void); 16820 16821/* the interface exported by the library */ 16822extern void do_something (void); 16823extern void do_something_else (void); 16824@end smallexample 16825 16826@noindent 16827Libraries built as explained above can be used from any program, provided 16828that the elaboration procedures (named @code{mylibinit} in the previous 16829example) are called before the library services are used. Any number of 16830libraries can be used simultaneously, as long as the elaboration 16831procedure of each library is called. 16832 16833Below is an example of a C program that uses the @code{mylib} library. 16834 16835@smallexample 16836#include "mylib_interface.h" 16837 16838int 16839main (void) 16840@{ 16841 /* First, elaborate the library before using it */ 16842 mylibinit (); 16843 16844 /* Main program, using the library exported entities */ 16845 do_something (); 16846 do_something_else (); 16847 16848 /* Library finalization at the end of the program */ 16849 mylibfinal (); 16850 return 0; 16851@} 16852@end smallexample 16853 16854@noindent 16855Note that invoking any library finalization procedure generated by 16856@code{gnatbind} shuts down the Ada run-time environment. 16857Consequently, the 16858finalization of all Ada libraries must be performed at the end of the program. 16859No call to these libraries or to the Ada run-time library should be made 16860after the finalization phase. 16861 16862@node Restrictions in Stand-alone Libraries 16863@subsection Restrictions in Stand-alone Libraries 16864 16865@noindent 16866The pragmas listed below should be used with caution inside libraries, 16867as they can create incompatibilities with other Ada libraries: 16868@itemize @bullet 16869@item pragma @code{Locking_Policy} 16870@item pragma @code{Queuing_Policy} 16871@item pragma @code{Task_Dispatching_Policy} 16872@item pragma @code{Unreserve_All_Interrupts} 16873@end itemize 16874 16875@noindent 16876When using a library that contains such pragmas, the user must make sure 16877that all libraries use the same pragmas with the same values. Otherwise, 16878@code{Program_Error} will 16879be raised during the elaboration of the conflicting 16880libraries. The usage of these pragmas and its consequences for the user 16881should therefore be well documented. 16882 16883Similarly, the traceback in the exception occurrence mechanism should be 16884enabled or disabled in a consistent manner across all libraries. 16885Otherwise, Program_Error will be raised during the elaboration of the 16886conflicting libraries. 16887 16888If the @code{Version} or @code{Body_Version} 16889attributes are used inside a library, then you need to 16890perform a @code{gnatbind} step that specifies all @file{ALI} files in all 16891libraries, so that version identifiers can be properly computed. 16892In practice these attributes are rarely used, so this is unlikely 16893to be a consideration. 16894 16895@node Rebuilding the GNAT Run-Time Library 16896@section Rebuilding the GNAT Run-Time Library 16897@cindex GNAT Run-Time Library, rebuilding 16898@cindex Building the GNAT Run-Time Library 16899@cindex Rebuilding the GNAT Run-Time Library 16900@cindex Run-Time Library, rebuilding 16901 16902@noindent 16903It may be useful to recompile the GNAT library in various contexts, the 16904most important one being the use of partition-wide configuration pragmas 16905such as @code{Normalize_Scalars}. A special Makefile called 16906@code{Makefile.adalib} is provided to that effect and can be found in 16907the directory containing the GNAT library. The location of this 16908directory depends on the way the GNAT environment has been installed and can 16909be determined by means of the command: 16910 16911@smallexample 16912$ gnatls -v 16913@end smallexample 16914 16915@noindent 16916The last entry in the object search path usually contains the 16917gnat library. This Makefile contains its own documentation and in 16918particular the set of instructions needed to rebuild a new library and 16919to use it. 16920 16921@node Using the GNU make Utility 16922@chapter Using the GNU @code{make} Utility 16923@findex make 16924 16925@noindent 16926This chapter offers some examples of makefiles that solve specific 16927problems. It does not explain how to write a makefile (@pxref{Top,, GNU 16928make, make, GNU @code{make}}), nor does it try to replace the 16929@command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}). 16930 16931All the examples in this section are specific to the GNU version of 16932make. Although @command{make} is a standard utility, and the basic language 16933is the same, these examples use some advanced features found only in 16934@code{GNU make}. 16935 16936@menu 16937* Using gnatmake in a Makefile:: 16938* Automatically Creating a List of Directories:: 16939* Generating the Command Line Switches:: 16940* Overcoming Command Line Length Limits:: 16941@end menu 16942 16943@node Using gnatmake in a Makefile 16944@section Using gnatmake in a Makefile 16945@findex makefile 16946@cindex GNU make 16947 16948@noindent 16949Complex project organizations can be handled in a very powerful way by 16950using GNU make combined with gnatmake. For instance, here is a Makefile 16951which allows you to build each subsystem of a big project into a separate 16952shared library. Such a makefile allows you to significantly reduce the link 16953time of very big applications while maintaining full coherence at 16954each step of the build process. 16955 16956The list of dependencies are handled automatically by 16957@command{gnatmake}. The Makefile is simply used to call gnatmake in each of 16958the appropriate directories. 16959 16960Note that you should also read the example on how to automatically 16961create the list of directories 16962(@pxref{Automatically Creating a List of Directories}) 16963which might help you in case your project has a lot of subdirectories. 16964 16965@smallexample 16966@iftex 16967@leftskip=0cm 16968@font@heightrm=cmr8 16969@heightrm 16970@end iftex 16971## This Makefile is intended to be used with the following directory 16972## configuration: 16973## - The sources are split into a series of csc (computer software components) 16974## Each of these csc is put in its own directory. 16975## Their name are referenced by the directory names. 16976## They will be compiled into shared library (although this would also work 16977## with static libraries 16978## - The main program (and possibly other packages that do not belong to any 16979## csc is put in the top level directory (where the Makefile is). 16980## toplevel_dir __ first_csc (sources) __ lib (will contain the library) 16981## \_ second_csc (sources) __ lib (will contain the library) 16982## \_ @dots{} 16983## Although this Makefile is build for shared library, it is easy to modify 16984## to build partial link objects instead (modify the lines with -shared and 16985## gnatlink below) 16986## 16987## With this makefile, you can change any file in the system or add any new 16988## file, and everything will be recompiled correctly (only the relevant shared 16989## objects will be recompiled, and the main program will be re-linked). 16990 16991# The list of computer software component for your project. This might be 16992# generated automatically. 16993CSC_LIST=aa bb cc 16994 16995# Name of the main program (no extension) 16996MAIN=main 16997 16998# If we need to build objects with -fPIC, uncomment the following line 16999#NEED_FPIC=-fPIC 17000 17001# The following variable should give the directory containing libgnat.so 17002# You can get this directory through 'gnatls -v'. This is usually the last 17003# directory in the Object_Path. 17004GLIB=@dots{} 17005 17006# The directories for the libraries 17007# (This macro expands the list of CSC to the list of shared libraries, you 17008# could simply use the expanded form: 17009# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so 17010LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@} 17011 17012$@{MAIN@}: objects $@{LIB_DIR@} 17013 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared 17014 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@} 17015 17016objects:: 17017 # recompile the sources 17018 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@} 17019 17020# Note: In a future version of GNAT, the following commands will be simplified 17021# by a new tool, gnatmlib 17022$@{LIB_DIR@}: 17023 mkdir -p $@{dir $@@ @} 17024 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat 17025 cd $@{dir $@@ @} && cp -f ../*.ali . 17026 17027# The dependencies for the modules 17028# Note that we have to force the expansion of *.o, since in some cases 17029# make won't be able to do it itself. 17030aa/lib/libaa.so: $@{wildcard aa/*.o@} 17031bb/lib/libbb.so: $@{wildcard bb/*.o@} 17032cc/lib/libcc.so: $@{wildcard cc/*.o@} 17033 17034# Make sure all of the shared libraries are in the path before starting the 17035# program 17036run:: 17037 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@} 17038 17039clean:: 17040 $@{RM@} -rf $@{CSC_LIST:%=%/lib@} 17041 $@{RM@} $@{CSC_LIST:%=%/*.ali@} 17042 $@{RM@} $@{CSC_LIST:%=%/*.o@} 17043 $@{RM@} *.o *.ali $@{MAIN@} 17044@end smallexample 17045 17046@node Automatically Creating a List of Directories 17047@section Automatically Creating a List of Directories 17048 17049@noindent 17050In most makefiles, you will have to specify a list of directories, and 17051store it in a variable. For small projects, it is often easier to 17052specify each of them by hand, since you then have full control over what 17053is the proper order for these directories, which ones should be 17054included. 17055 17056However, in larger projects, which might involve hundreds of 17057subdirectories, it might be more convenient to generate this list 17058automatically. 17059 17060The example below presents two methods. The first one, although less 17061general, gives you more control over the list. It involves wildcard 17062characters, that are automatically expanded by @command{make}. Its 17063shortcoming is that you need to explicitly specify some of the 17064organization of your project, such as for instance the directory tree 17065depth, whether some directories are found in a separate tree, @enddots{} 17066 17067The second method is the most general one. It requires an external 17068program, called @command{find}, which is standard on all Unix systems. All 17069the directories found under a given root directory will be added to the 17070list. 17071 17072@smallexample 17073@iftex 17074@leftskip=0cm 17075@font@heightrm=cmr8 17076@heightrm 17077@end iftex 17078# The examples below are based on the following directory hierarchy: 17079# All the directories can contain any number of files 17080# ROOT_DIRECTORY -> a -> aa -> aaa 17081# -> ab 17082# -> ac 17083# -> b -> ba -> baa 17084# -> bb 17085# -> bc 17086# This Makefile creates a variable called DIRS, that can be reused any time 17087# you need this list (see the other examples in this section) 17088 17089# The root of your project's directory hierarchy 17090ROOT_DIRECTORY=. 17091 17092#### 17093# First method: specify explicitly the list of directories 17094# This allows you to specify any subset of all the directories you need. 17095#### 17096 17097DIRS := a/aa/ a/ab/ b/ba/ 17098 17099#### 17100# Second method: use wildcards 17101# Note that the argument(s) to wildcard below should end with a '/'. 17102# Since wildcards also return file names, we have to filter them out 17103# to avoid duplicate directory names. 17104# We thus use make's @code{dir} and @code{sort} functions. 17105# It sets DIRs to the following value (note that the directories aaa and baa 17106# are not given, unless you change the arguments to wildcard). 17107# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/ 17108#### 17109 17110DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ 17111 $@{ROOT_DIRECTORY@}/*/*/@}@}@} 17112 17113#### 17114# Third method: use an external program 17115# This command is much faster if run on local disks, avoiding NFS slowdowns. 17116# This is the most complete command: it sets DIRs to the following value: 17117# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc 17118#### 17119 17120DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@} 17121 17122@end smallexample 17123 17124@node Generating the Command Line Switches 17125@section Generating the Command Line Switches 17126 17127@noindent 17128Once you have created the list of directories as explained in the 17129previous section (@pxref{Automatically Creating a List of Directories}), 17130you can easily generate the command line arguments to pass to gnatmake. 17131 17132For the sake of completeness, this example assumes that the source path 17133is not the same as the object path, and that you have two separate lists 17134of directories. 17135 17136@smallexample 17137# see "Automatically creating a list of directories" to create 17138# these variables 17139SOURCE_DIRS= 17140OBJECT_DIRS= 17141 17142GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@} 17143GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@} 17144 17145all: 17146 gnatmake $@{GNATMAKE_SWITCHES@} main_unit 17147@end smallexample 17148 17149@node Overcoming Command Line Length Limits 17150@section Overcoming Command Line Length Limits 17151 17152@noindent 17153One problem that might be encountered on big projects is that many 17154operating systems limit the length of the command line. It is thus hard to give 17155gnatmake the list of source and object directories. 17156 17157This example shows how you can set up environment variables, which will 17158make @command{gnatmake} behave exactly as if the directories had been 17159specified on the command line, but have a much higher length limit (or 17160even none on most systems). 17161 17162It assumes that you have created a list of directories in your Makefile, 17163using one of the methods presented in 17164@ref{Automatically Creating a List of Directories}. 17165For the sake of completeness, we assume that the object 17166path (where the ALI files are found) is different from the sources patch. 17167 17168Note a small trick in the Makefile below: for efficiency reasons, we 17169create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are 17170expanded immediately by @code{make}. This way we overcome the standard 17171make behavior which is to expand the variables only when they are 17172actually used. 17173 17174On Windows, if you are using the standard Windows command shell, you must 17175replace colons with semicolons in the assignments to these variables. 17176 17177@smallexample 17178@iftex 17179@leftskip=0cm 17180@font@heightrm=cmr8 17181@heightrm 17182@end iftex 17183# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH. 17184# This is the same thing as putting the -I arguments on the command line. 17185# (the equivalent of using -aI on the command line would be to define 17186# only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH). 17187# You can of course have different values for these variables. 17188# 17189# Note also that we need to keep the previous values of these variables, since 17190# they might have been set before running 'make' to specify where the GNAT 17191# library is installed. 17192 17193# see "Automatically creating a list of directories" to create these 17194# variables 17195SOURCE_DIRS= 17196OBJECT_DIRS= 17197 17198empty:= 17199space:=$@{empty@} $@{empty@} 17200SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@} 17201OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@} 17202ADA_INCLUDE_PATH += $@{SOURCE_LIST@} 17203ADA_OBJECTS_PATH += $@{OBJECT_LIST@} 17204export ADA_INCLUDE_PATH 17205export ADA_OBJECTS_PATH 17206 17207all: 17208 gnatmake main_unit 17209@end smallexample 17210@end ifclear 17211 17212@node Memory Management Issues 17213@chapter Memory Management Issues 17214 17215@noindent 17216This chapter describes some useful memory pools provided in the GNAT library 17217and in particular the GNAT Debug Pool facility, which can be used to detect 17218incorrect uses of access values (including ``dangling references''). 17219@ifclear vms 17220It also describes the @command{gnatmem} tool, which can be used to track down 17221``memory leaks''. 17222@end ifclear 17223 17224@menu 17225* Some Useful Memory Pools:: 17226* The GNAT Debug Pool Facility:: 17227@ifclear vms 17228* The gnatmem Tool:: 17229@end ifclear 17230@end menu 17231 17232@node Some Useful Memory Pools 17233@section Some Useful Memory Pools 17234@findex Memory Pool 17235@cindex storage, pool 17236 17237@noindent 17238The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool 17239storage pool. Allocations use the standard system call @code{malloc} while 17240deallocations use the standard system call @code{free}. No reclamation is 17241performed when the pool goes out of scope. For performance reasons, the 17242standard default Ada allocators/deallocators do not use any explicit storage 17243pools but if they did, they could use this storage pool without any change in 17244behavior. That is why this storage pool is used when the user 17245manages to make the default implicit allocator explicit as in this example: 17246@smallexample @c ada 17247 type T1 is access Something; 17248 -- no Storage pool is defined for T2 17249 type T2 is access Something_Else; 17250 for T2'Storage_Pool use T1'Storage_Pool; 17251 -- the above is equivalent to 17252 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object; 17253@end smallexample 17254 17255@noindent 17256The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage 17257pool. The allocation strategy is similar to @code{Pool_Local}'s 17258except that the all 17259storage allocated with this pool is reclaimed when the pool object goes out of 17260scope. This pool provides a explicit mechanism similar to the implicit one 17261provided by several Ada 83 compilers for allocations performed through a local 17262access type and whose purpose was to reclaim memory when exiting the 17263scope of a given local access. As an example, the following program does not 17264leak memory even though it does not perform explicit deallocation: 17265 17266@smallexample @c ada 17267with System.Pool_Local; 17268procedure Pooloc1 is 17269 procedure Internal is 17270 type A is access Integer; 17271 X : System.Pool_Local.Unbounded_Reclaim_Pool; 17272 for A'Storage_Pool use X; 17273 v : A; 17274 begin 17275 for I in 1 .. 50 loop 17276 v := new Integer; 17277 end loop; 17278 end Internal; 17279begin 17280 for I in 1 .. 100 loop 17281 Internal; 17282 end loop; 17283end Pooloc1; 17284@end smallexample 17285 17286@noindent 17287The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when 17288@code{Storage_Size} is specified for an access type. 17289The whole storage for the pool is 17290allocated at once, usually on the stack at the point where the access type is 17291elaborated. It is automatically reclaimed when exiting the scope where the 17292access type is defined. This package is not intended to be used directly by the 17293user and it is implicitly used for each such declaration: 17294 17295@smallexample @c ada 17296 type T1 is access Something; 17297 for T1'Storage_Size use 10_000; 17298@end smallexample 17299 17300@node The GNAT Debug Pool Facility 17301@section The GNAT Debug Pool Facility 17302@findex Debug Pool 17303@cindex storage, pool, memory corruption 17304 17305@noindent 17306The use of unchecked deallocation and unchecked conversion can easily 17307lead to incorrect memory references. The problems generated by such 17308references are usually difficult to tackle because the symptoms can be 17309very remote from the origin of the problem. In such cases, it is 17310very helpful to detect the problem as early as possible. This is the 17311purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}. 17312 17313In order to use the GNAT specific debugging pool, the user must 17314associate a debug pool object with each of the access types that may be 17315related to suspected memory problems. See Ada Reference Manual 13.11. 17316@smallexample @c ada 17317type Ptr is access Some_Type; 17318Pool : GNAT.Debug_Pools.Debug_Pool; 17319for Ptr'Storage_Pool use Pool; 17320@end smallexample 17321 17322@noindent 17323@code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of 17324pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools, 17325allow the user to redefine allocation and deallocation strategies. They 17326also provide a checkpoint for each dereference, through the use of 17327the primitive operation @code{Dereference} which is implicitly called at 17328each dereference of an access value. 17329 17330Once an access type has been associated with a debug pool, operations on 17331values of the type may raise four distinct exceptions, 17332which correspond to four potential kinds of memory corruption: 17333@itemize @bullet 17334@item 17335@code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage} 17336@item 17337@code{GNAT.Debug_Pools.Accessing_Deallocated_Storage} 17338@item 17339@code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage} 17340@item 17341@code{GNAT.Debug_Pools.Freeing_Deallocated_Storage } 17342@end itemize 17343 17344@noindent 17345For types associated with a Debug_Pool, dynamic allocation is performed using 17346the standard GNAT allocation routine. References to all allocated chunks of 17347memory are kept in an internal dictionary. Several deallocation strategies are 17348provided, whereupon the user can choose to release the memory to the system, 17349keep it allocated for further invalid access checks, or fill it with an easily 17350recognizable pattern for debug sessions. The memory pattern is the old IBM 17351hexadecimal convention: @code{16#DEADBEEF#}. 17352 17353See the documentation in the file g-debpoo.ads for more information on the 17354various strategies. 17355 17356Upon each dereference, a check is made that the access value denotes a 17357properly allocated memory location. Here is a complete example of use of 17358@code{Debug_Pools}, that includes typical instances of memory corruption: 17359@smallexample @c ada 17360@iftex 17361@leftskip=0cm 17362@end iftex 17363with Gnat.Io; use Gnat.Io; 17364with Unchecked_Deallocation; 17365with Unchecked_Conversion; 17366with GNAT.Debug_Pools; 17367with System.Storage_Elements; 17368with Ada.Exceptions; use Ada.Exceptions; 17369procedure Debug_Pool_Test is 17370 17371 type T is access Integer; 17372 type U is access all T; 17373 17374 P : GNAT.Debug_Pools.Debug_Pool; 17375 for T'Storage_Pool use P; 17376 17377 procedure Free is new Unchecked_Deallocation (Integer, T); 17378 function UC is new Unchecked_Conversion (U, T); 17379 A, B : aliased T; 17380 17381 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line); 17382 17383begin 17384 Info (P); 17385 A := new Integer; 17386 B := new Integer; 17387 B := A; 17388 Info (P); 17389 Free (A); 17390 begin 17391 Put_Line (Integer'Image(B.all)); 17392 exception 17393 when E : others => Put_Line ("raised: " & Exception_Name (E)); 17394 end; 17395 begin 17396 Free (B); 17397 exception 17398 when E : others => Put_Line ("raised: " & Exception_Name (E)); 17399 end; 17400 B := UC(A'Access); 17401 begin 17402 Put_Line (Integer'Image(B.all)); 17403 exception 17404 when E : others => Put_Line ("raised: " & Exception_Name (E)); 17405 end; 17406 begin 17407 Free (B); 17408 exception 17409 when E : others => Put_Line ("raised: " & Exception_Name (E)); 17410 end; 17411 Info (P); 17412end Debug_Pool_Test; 17413@end smallexample 17414 17415@noindent 17416The debug pool mechanism provides the following precise diagnostics on the 17417execution of this erroneous program: 17418@smallexample 17419Debug Pool info: 17420 Total allocated bytes : 0 17421 Total deallocated bytes : 0 17422 Current Water Mark: 0 17423 High Water Mark: 0 17424 17425Debug Pool info: 17426 Total allocated bytes : 8 17427 Total deallocated bytes : 0 17428 Current Water Mark: 8 17429 High Water Mark: 8 17430 17431raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE 17432raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE 17433raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE 17434raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE 17435Debug Pool info: 17436 Total allocated bytes : 8 17437 Total deallocated bytes : 4 17438 Current Water Mark: 4 17439 High Water Mark: 8 17440@end smallexample 17441 17442@ifclear vms 17443@node The gnatmem Tool 17444@section The @command{gnatmem} Tool 17445@findex gnatmem 17446 17447@noindent 17448The @code{gnatmem} utility monitors dynamic allocation and 17449deallocation activity in a program, and displays information about 17450incorrect deallocations and possible sources of memory leaks. 17451It is designed to work in association with a static runtime library 17452only and in this context provides three types of information: 17453@itemize @bullet 17454@item 17455General information concerning memory management, such as the total 17456number of allocations and deallocations, the amount of allocated 17457memory and the high water mark, i.e.@: the largest amount of allocated 17458memory in the course of program execution. 17459 17460@item 17461Backtraces for all incorrect deallocations, that is to say deallocations 17462which do not correspond to a valid allocation. 17463 17464@item 17465Information on each allocation that is potentially the origin of a memory 17466leak. 17467@end itemize 17468 17469@menu 17470* Running gnatmem:: 17471* Switches for gnatmem:: 17472* Example of gnatmem Usage:: 17473@end menu 17474 17475@node Running gnatmem 17476@subsection Running @code{gnatmem} 17477 17478@noindent 17479@code{gnatmem} makes use of the output created by the special version of 17480allocation and deallocation routines that record call information. This 17481allows to obtain accurate dynamic memory usage history at a minimal cost to 17482the execution speed. Note however, that @code{gnatmem} is not supported on 17483all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, 17484Solaris and Windows NT/2000/XP (x86). 17485 17486@noindent 17487The @code{gnatmem} command has the form 17488 17489@smallexample 17490@c $ gnatmem @ovar{switches} user_program 17491@c Expanding @ovar macro inline (explanation in macro def comments) 17492 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program} 17493@end smallexample 17494 17495@noindent 17496The program must have been linked with the instrumented version of the 17497allocation and deallocation routines. This is done by linking with the 17498@file{libgmem.a} library. For correct symbolic backtrace information, 17499the user program should be compiled with debugging options 17500(see @ref{Switches for gcc}). For example to build @file{my_program}: 17501 17502@smallexample 17503$ gnatmake -g my_program -largs -lgmem 17504@end smallexample 17505 17506@noindent 17507As library @file{libgmem.a} contains an alternate body for package 17508@code{System.Memory}, @file{s-memory.adb} should not be compiled and linked 17509when an executable is linked with library @file{libgmem.a}. It is then not 17510recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}. 17511 17512@noindent 17513When @file{my_program} is executed, the file @file{gmem.out} is produced. 17514This file contains information about all allocations and deallocations 17515performed by the program. It is produced by the instrumented allocations and 17516deallocations routines and will be used by @code{gnatmem}. 17517 17518In order to produce symbolic backtrace information for allocations and 17519deallocations performed by the GNAT run-time library, you need to use a 17520version of that library that has been compiled with the @option{-g} switch 17521(see @ref{Rebuilding the GNAT Run-Time Library}). 17522 17523Gnatmem must be supplied with the @file{gmem.out} file and the executable to 17524examine. If the location of @file{gmem.out} file was not explicitly supplied by 17525@option{-i} switch, gnatmem will assume that this file can be found in the 17526current directory. For example, after you have executed @file{my_program}, 17527@file{gmem.out} can be analyzed by @code{gnatmem} using the command: 17528 17529@smallexample 17530$ gnatmem my_program 17531@end smallexample 17532 17533@noindent 17534This will produce the output with the following format: 17535 17536*************** debut cc 17537@smallexample 17538$ gnatmem my_program 17539 17540Global information 17541------------------ 17542 Total number of allocations : 45 17543 Total number of deallocations : 6 17544 Final Water Mark (non freed mem) : 11.29 Kilobytes 17545 High Water Mark : 11.40 Kilobytes 17546 17547. 17548. 17549. 17550Allocation Root # 2 17551------------------- 17552 Number of non freed allocations : 11 17553 Final Water Mark (non freed mem) : 1.16 Kilobytes 17554 High Water Mark : 1.27 Kilobytes 17555 Backtrace : 17556 my_program.adb:23 my_program.alloc 17557. 17558. 17559. 17560@end smallexample 17561 17562The first block of output gives general information. In this case, the 17563Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an 17564Unchecked_Deallocation routine occurred. 17565 17566@noindent 17567Subsequent paragraphs display information on all allocation roots. 17568An allocation root is a specific point in the execution of the program 17569that generates some dynamic allocation, such as a ``@code{@b{new}}'' 17570construct. This root is represented by an execution backtrace (or subprogram 17571call stack). By default the backtrace depth for allocations roots is 1, so 17572that a root corresponds exactly to a source location. The backtrace can 17573be made deeper, to make the root more specific. 17574 17575@node Switches for gnatmem 17576@subsection Switches for @code{gnatmem} 17577 17578@noindent 17579@code{gnatmem} recognizes the following switches: 17580 17581@table @option 17582 17583@item -q 17584@cindex @option{-q} (@code{gnatmem}) 17585Quiet. Gives the minimum output needed to identify the origin of the 17586memory leaks. Omits statistical information. 17587 17588@item @var{N} 17589@cindex @var{N} (@code{gnatmem}) 17590N is an integer literal (usually between 1 and 10) which controls the 17591depth of the backtraces defining allocation root. The default value for 17592N is 1. The deeper the backtrace, the more precise the localization of 17593the root. Note that the total number of roots can depend on this 17594parameter. This parameter must be specified @emph{before} the name of the 17595executable to be analyzed, to avoid ambiguity. 17596 17597@item -b n 17598@cindex @option{-b} (@code{gnatmem}) 17599This switch has the same effect as just depth parameter. 17600 17601@item -i @var{file} 17602@cindex @option{-i} (@code{gnatmem}) 17603Do the @code{gnatmem} processing starting from @file{file}, rather than 17604@file{gmem.out} in the current directory. 17605 17606@item -m n 17607@cindex @option{-m} (@code{gnatmem}) 17608This switch causes @code{gnatmem} to mask the allocation roots that have less 17609than n leaks. The default value is 1. Specifying the value of 0 will allow to 17610examine even the roots that didn't result in leaks. 17611 17612@item -s order 17613@cindex @option{-s} (@code{gnatmem}) 17614This switch causes @code{gnatmem} to sort the allocation roots according to the 17615specified order of sort criteria, each identified by a single letter. The 17616currently supported criteria are @code{n, h, w} standing respectively for 17617number of unfreed allocations, high watermark, and final watermark 17618corresponding to a specific root. The default order is @code{nwh}. 17619 17620@end table 17621 17622@node Example of gnatmem Usage 17623@subsection Example of @code{gnatmem} Usage 17624 17625@noindent 17626The following example shows the use of @code{gnatmem} 17627on a simple memory-leaking program. 17628Suppose that we have the following Ada program: 17629 17630@smallexample @c ada 17631@group 17632@cartouche 17633with Unchecked_Deallocation; 17634procedure Test_Gm is 17635 17636 type T is array (1..1000) of Integer; 17637 type Ptr is access T; 17638 procedure Free is new Unchecked_Deallocation (T, Ptr); 17639 A : Ptr; 17640 17641 procedure My_Alloc is 17642 begin 17643 A := new T; 17644 end My_Alloc; 17645 17646 procedure My_DeAlloc is 17647 B : Ptr := A; 17648 begin 17649 Free (B); 17650 end My_DeAlloc; 17651 17652begin 17653 My_Alloc; 17654 for I in 1 .. 5 loop 17655 for J in I .. 5 loop 17656 My_Alloc; 17657 end loop; 17658 My_Dealloc; 17659 end loop; 17660end; 17661@end cartouche 17662@end group 17663@end smallexample 17664 17665@noindent 17666The program needs to be compiled with debugging option and linked with 17667@code{gmem} library: 17668 17669@smallexample 17670$ gnatmake -g test_gm -largs -lgmem 17671@end smallexample 17672 17673@noindent 17674Then we execute the program as usual: 17675 17676@smallexample 17677$ test_gm 17678@end smallexample 17679 17680@noindent 17681Then @code{gnatmem} is invoked simply with 17682@smallexample 17683$ gnatmem test_gm 17684@end smallexample 17685 17686@noindent 17687which produces the following output (result may vary on different platforms): 17688 17689@smallexample 17690Global information 17691------------------ 17692 Total number of allocations : 18 17693 Total number of deallocations : 5 17694 Final Water Mark (non freed mem) : 53.00 Kilobytes 17695 High Water Mark : 56.90 Kilobytes 17696 17697Allocation Root # 1 17698------------------- 17699 Number of non freed allocations : 11 17700 Final Water Mark (non freed mem) : 42.97 Kilobytes 17701 High Water Mark : 46.88 Kilobytes 17702 Backtrace : 17703 test_gm.adb:11 test_gm.my_alloc 17704 17705Allocation Root # 2 17706------------------- 17707 Number of non freed allocations : 1 17708 Final Water Mark (non freed mem) : 10.02 Kilobytes 17709 High Water Mark : 10.02 Kilobytes 17710 Backtrace : 17711 s-secsta.adb:81 system.secondary_stack.ss_init 17712 17713Allocation Root # 3 17714------------------- 17715 Number of non freed allocations : 1 17716 Final Water Mark (non freed mem) : 12 Bytes 17717 High Water Mark : 12 Bytes 17718 Backtrace : 17719 s-secsta.adb:181 system.secondary_stack.ss_init 17720@end smallexample 17721 17722@noindent 17723Note that the GNAT run time contains itself a certain number of 17724allocations that have no corresponding deallocation, 17725as shown here for root #2 and root 17726#3. This is a normal behavior when the number of non-freed allocations 17727is one, it allocates dynamic data structures that the run time needs for 17728the complete lifetime of the program. Note also that there is only one 17729allocation root in the user program with a single line back trace: 17730test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the 17731program shows that 'My_Alloc' is called at 2 different points in the 17732source (line 21 and line 24). If those two allocation roots need to be 17733distinguished, the backtrace depth parameter can be used: 17734 17735@smallexample 17736$ gnatmem 3 test_gm 17737@end smallexample 17738 17739@noindent 17740which will give the following output: 17741 17742@smallexample 17743Global information 17744------------------ 17745 Total number of allocations : 18 17746 Total number of deallocations : 5 17747 Final Water Mark (non freed mem) : 53.00 Kilobytes 17748 High Water Mark : 56.90 Kilobytes 17749 17750Allocation Root # 1 17751------------------- 17752 Number of non freed allocations : 10 17753 Final Water Mark (non freed mem) : 39.06 Kilobytes 17754 High Water Mark : 42.97 Kilobytes 17755 Backtrace : 17756 test_gm.adb:11 test_gm.my_alloc 17757 test_gm.adb:24 test_gm 17758 b_test_gm.c:52 main 17759 17760Allocation Root # 2 17761------------------- 17762 Number of non freed allocations : 1 17763 Final Water Mark (non freed mem) : 10.02 Kilobytes 17764 High Water Mark : 10.02 Kilobytes 17765 Backtrace : 17766 s-secsta.adb:81 system.secondary_stack.ss_init 17767 s-secsta.adb:283 <system__secondary_stack___elabb> 17768 b_test_gm.c:33 adainit 17769 17770Allocation Root # 3 17771------------------- 17772 Number of non freed allocations : 1 17773 Final Water Mark (non freed mem) : 3.91 Kilobytes 17774 High Water Mark : 3.91 Kilobytes 17775 Backtrace : 17776 test_gm.adb:11 test_gm.my_alloc 17777 test_gm.adb:21 test_gm 17778 b_test_gm.c:52 main 17779 17780Allocation Root # 4 17781------------------- 17782 Number of non freed allocations : 1 17783 Final Water Mark (non freed mem) : 12 Bytes 17784 High Water Mark : 12 Bytes 17785 Backtrace : 17786 s-secsta.adb:181 system.secondary_stack.ss_init 17787 s-secsta.adb:283 <system__secondary_stack___elabb> 17788 b_test_gm.c:33 adainit 17789@end smallexample 17790 17791@noindent 17792The allocation root #1 of the first example has been split in 2 roots #1 17793and #3 thanks to the more precise associated backtrace. 17794 17795@end ifclear 17796 17797@node Stack Related Facilities 17798@chapter Stack Related Facilities 17799 17800@noindent 17801This chapter describes some useful tools associated with stack 17802checking and analysis. In 17803particular, it deals with dynamic and static stack usage measurements. 17804 17805@menu 17806* Stack Overflow Checking:: 17807* Static Stack Usage Analysis:: 17808* Dynamic Stack Usage Analysis:: 17809@end menu 17810 17811@node Stack Overflow Checking 17812@section Stack Overflow Checking 17813@cindex Stack Overflow Checking 17814@cindex -fstack-check 17815 17816@noindent 17817For most operating systems, @command{gcc} does not perform stack overflow 17818checking by default. This means that if the main environment task or 17819some other task exceeds the available stack space, then unpredictable 17820behavior will occur. Most native systems offer some level of protection by 17821adding a guard page at the end of each task stack. This mechanism is usually 17822not enough for dealing properly with stack overflow situations because 17823a large local variable could ``jump'' above the guard page. 17824Furthermore, when the 17825guard page is hit, there may not be any space left on the stack for executing 17826the exception propagation code. Enabling stack checking avoids 17827such situations. 17828 17829To activate stack checking, compile all units with the gcc option 17830@option{-fstack-check}. For example: 17831 17832@smallexample 17833gcc -c -fstack-check package1.adb 17834@end smallexample 17835 17836@noindent 17837Units compiled with this option will generate extra instructions to check 17838that any use of the stack (for procedure calls or for declaring local 17839variables in declare blocks) does not exceed the available stack space. 17840If the space is exceeded, then a @code{Storage_Error} exception is raised. 17841 17842For declared tasks, the stack size is controlled by the size 17843given in an applicable @code{Storage_Size} pragma or by the value specified 17844at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to 17845the default size as defined in the GNAT runtime otherwise. 17846 17847For the environment task, the stack size depends on 17848system defaults and is unknown to the compiler. Stack checking 17849may still work correctly if a fixed 17850size stack is allocated, but this cannot be guaranteed. 17851@ifclear vms 17852To ensure that a clean exception is signalled for stack 17853overflow, set the environment variable 17854@env{GNAT_STACK_LIMIT} to indicate the maximum 17855stack area that can be used, as in: 17856@cindex GNAT_STACK_LIMIT 17857 17858@smallexample 17859SET GNAT_STACK_LIMIT 1600 17860@end smallexample 17861 17862@noindent 17863The limit is given in kilobytes, so the above declaration would 17864set the stack limit of the environment task to 1.6 megabytes. 17865Note that the only purpose of this usage is to limit the amount 17866of stack used by the environment task. If it is necessary to 17867increase the amount of stack for the environment task, then this 17868is an operating systems issue, and must be addressed with the 17869appropriate operating systems commands. 17870@end ifclear 17871@ifset vms 17872To have a fixed size stack in the environment task, the stack must be put 17873in the P0 address space and its size specified. Use these switches to 17874create a p0 image: 17875 17876@smallexample 17877gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image" 17878@end smallexample 17879 17880@noindent 17881The quotes are required to keep case. The number after @samp{STACK=} is the 17882size of the environmental task stack in pagelets (512 bytes). In this example 17883the stack size is about 2 megabytes. 17884 17885@noindent 17886A consequence of the @option{/p0image} qualifier is also to makes RMS buffers 17887be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for 17888more details about the @option{/p0image} qualifier and the @option{stack} 17889option. 17890 17891@noindent 17892On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and 17893@samp{GNAT_RBS_SIZE} logicals to the size of the primary and register 17894stack in kilobytes. For example: 17895 17896@smallexample 17897$ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB. 17898@end smallexample 17899@end ifset 17900 17901@node Static Stack Usage Analysis 17902@section Static Stack Usage Analysis 17903@cindex Static Stack Usage Analysis 17904@cindex -fstack-usage 17905 17906@noindent 17907A unit compiled with @option{-fstack-usage} will generate an extra file 17908that specifies 17909the maximum amount of stack used, on a per-function basis. 17910The file has the same 17911basename as the target object file with a @file{.su} extension. 17912Each line of this file is made up of three fields: 17913 17914@itemize 17915@item 17916The name of the function. 17917@item 17918A number of bytes. 17919@item 17920One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}. 17921@end itemize 17922 17923The second field corresponds to the size of the known part of the function 17924frame. 17925 17926The qualifier @code{static} means that the function frame size 17927is purely static. 17928It usually means that all local variables have a static size. 17929In this case, the second field is a reliable measure of the function stack 17930utilization. 17931 17932The qualifier @code{dynamic} means that the function frame size is not static. 17933It happens mainly when some local variables have a dynamic size. When this 17934qualifier appears alone, the second field is not a reliable measure 17935of the function stack analysis. When it is qualified with @code{bounded}, it 17936means that the second field is a reliable maximum of the function stack 17937utilization. 17938 17939A unit compiled with @option{-Wstack-usage} will issue a warning for each 17940subprogram whose stack usage might be larger than the specified amount of 17941bytes. The wording is in keeping with the qualifier documented above. 17942 17943@node Dynamic Stack Usage Analysis 17944@section Dynamic Stack Usage Analysis 17945 17946@noindent 17947It is possible to measure the maximum amount of stack used by a task, by 17948adding a switch to @command{gnatbind}, as: 17949 17950@smallexample 17951$ gnatbind -u0 file 17952@end smallexample 17953 17954@noindent 17955With this option, at each task termination, its stack usage is output on 17956@file{stderr}. 17957It is not always convenient to output the stack usage when the program 17958is still running. Hence, it is possible to delay this output until program 17959termination. for a given number of tasks specified as the argument of the 17960@option{-u} option. For instance: 17961 17962@smallexample 17963$ gnatbind -u100 file 17964@end smallexample 17965 17966@noindent 17967will buffer the stack usage information of the first 100 tasks to terminate and 17968output this info at program termination. Results are displayed in four 17969columns: 17970 17971@noindent 17972Index | Task Name | Stack Size | Stack Usage 17973 17974@noindent 17975where: 17976 17977@table @emph 17978@item Index 17979is a number associated with each task. 17980 17981@item Task Name 17982is the name of the task analyzed. 17983 17984@item Stack Size 17985is the maximum size for the stack. 17986 17987@item Stack Usage 17988is the measure done by the stack analyzer. In order to prevent overflow, the stack 17989is not entirely analyzed, and it's not possible to know exactly how 17990much has actually been used. 17991 17992@end table 17993 17994@noindent 17995The environment task stack, e.g., the stack that contains the main unit, is 17996only processed when the environment variable GNAT_STACK_LIMIT is set. 17997 17998@noindent 17999The package @code{GNAT.Task_Stack_Usage} provides facilities to get 18000stack usage reports at run-time. See its body for the details. 18001 18002@c ********************************* 18003@c * GNATCHECK * 18004@c ********************************* 18005@node Verifying Properties Using gnatcheck 18006@chapter Verifying Properties Using @command{gnatcheck} 18007@findex gnatcheck 18008@cindex @command{gnatcheck} 18009 18010@noindent 18011The @command{gnatcheck} tool is an ASIS-based utility that checks properties 18012of Ada source files according to a given set of semantic rules. 18013@cindex ASIS 18014 18015In order to check compliance with a given rule, @command{gnatcheck} has to 18016semantically analyze the Ada sources. 18017Therefore, checks can only be performed on 18018legal Ada units. Moreover, when a unit depends semantically upon units located 18019outside the current directory, the source search path has to be provided when 18020calling @command{gnatcheck}, either through a specified project file or 18021through @command{gnatcheck} switches. 18022 18023For full details, refer to @cite{GNATcheck Reference Manual} document. 18024 18025 18026@c ********************************* 18027@node Creating Sample Bodies Using gnatstub 18028@chapter Creating Sample Bodies Using @command{gnatstub} 18029@findex gnatstub 18030 18031@noindent 18032@command{gnatstub} creates body stubs, that is, empty but compilable bodies 18033for library unit declarations. 18034 18035Note: to invoke @code{gnatstub} with a project file, use the @code{gnat} 18036driver (see @ref{The GNAT Driver and Project Files}). 18037 18038To create a body stub, @command{gnatstub} has to compile the library 18039unit declaration. Therefore, bodies can be created only for legal 18040library units. Moreover, if a library unit depends semantically upon 18041units located outside the current directory, you have to provide 18042the source search path when calling @command{gnatstub}, see the description 18043of @command{gnatstub} switches below. 18044 18045By default, all the program unit body stubs generated by @code{gnatstub} 18046raise the predefined @code{Program_Error} exception, which will catch 18047accidental calls of generated stubs. This behavior can be changed with 18048option @option{^--no-exception^/NO_EXCEPTION^} (see below). 18049 18050@menu 18051* Running gnatstub:: 18052* Switches for gnatstub:: 18053@end menu 18054 18055@node Running gnatstub 18056@section Running @command{gnatstub} 18057 18058@noindent 18059@command{gnatstub} has a command-line interface of the form: 18060 18061@smallexample 18062@c $ gnatstub @ovar{switches} @var{filename} @ovar{directory} 18063@c Expanding @ovar macro inline (explanation in macro def comments) 18064$ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]} 18065@end smallexample 18066 18067@noindent 18068where 18069@table @var 18070@item filename 18071is the name of the source file that contains a library unit declaration 18072for which a body must be created. The file name may contain the path 18073information. 18074The file name does not have to follow the GNAT file name conventions. If the 18075name 18076does not follow GNAT file naming conventions, the name of the body file must 18077be provided 18078explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option. 18079If the file name follows the GNAT file naming 18080conventions and the name of the body file is not provided, 18081@command{gnatstub} 18082creates the name 18083of the body file from the argument file name by replacing the @file{.ads} 18084suffix 18085with the @file{.adb} suffix. 18086 18087@item directory 18088indicates the directory in which the body stub is to be placed (the default 18089is the 18090current directory) 18091 18092@item @samp{@var{gcc_switches}} is a list of switches for 18093@command{gcc}. They will be passed on to all compiler invocations made by 18094@command{gnatstub} to generate the ASIS trees. Here you can provide 18095@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path, 18096use the @option{-gnatec} switch to set the configuration file, 18097use the @option{-gnat05} switch if sources should be compiled in 18098Ada 2005 mode etc. 18099 18100@item switches 18101is an optional sequence of switches as described in the next section 18102@end table 18103 18104@node Switches for gnatstub 18105@section Switches for @command{gnatstub} 18106 18107@table @option 18108@c !sort! 18109 18110@item ^-f^/FULL^ 18111@cindex @option{^-f^/FULL^} (@command{gnatstub}) 18112If the destination directory already contains a file with the name of the 18113body file 18114for the argument spec file, replace it with the generated body stub. 18115 18116@item ^-hs^/HEADER=SPEC^ 18117@cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub}) 18118Put the comment header (i.e., all the comments preceding the 18119compilation unit) from the source of the library unit declaration 18120into the body stub. 18121 18122@item ^-hg^/HEADER=GENERAL^ 18123@cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub}) 18124Put a sample comment header into the body stub. 18125 18126@item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^ 18127@cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub}) 18128Use the content of the file as the comment header for a generated body stub. 18129 18130@ifclear vms 18131@item -IDIR 18132@cindex @option{-IDIR} (@command{gnatstub}) 18133@itemx -I- 18134@cindex @option{-I-} (@command{gnatstub}) 18135@end ifclear 18136@ifset vms 18137@item /NOCURRENT_DIRECTORY 18138@cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub}) 18139@end ifset 18140^These switches have ^This switch has^ the same meaning as in calls to 18141@command{gcc}. 18142^They define ^It defines ^ the source search path in the call to 18143@command{gcc} issued 18144by @command{gnatstub} to compile an argument source file. 18145 18146@item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH} 18147@cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub}) 18148This switch has the same meaning as in calls to @command{gcc}. 18149It defines the additional configuration file to be passed to the call to 18150@command{gcc} issued 18151by @command{gnatstub} to compile an argument source file. 18152 18153@item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n} 18154@cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub}) 18155(@var{n} is a non-negative integer). Set the maximum line length in the 18156body stub to @var{n}; the default is 79. The maximum value that can be 18157specified is 32767. Note that in the special case of configuration 18158pragma files, the maximum is always 32767 regardless of whether or 18159not this switch appears. 18160 18161@item ^-gnaty^/STYLE_CHECKS=^@var{n} 18162@cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub}) 18163(@var{n} is a non-negative integer from 1 to 9). Set the indentation level in 18164the generated body sample to @var{n}. 18165The default indentation is 3. 18166 18167@item ^-gnatyo^/ORDERED_SUBPROGRAMS^ 18168@cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub}) 18169Order local bodies alphabetically. (By default local bodies are ordered 18170in the same way as the corresponding local specs in the argument spec file.) 18171 18172@item ^-i^/INDENTATION=^@var{n} 18173@cindex @option{^-i^/INDENTATION^} (@command{gnatstub}) 18174Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}} 18175 18176@item ^-k^/TREE_FILE=SAVE^ 18177@cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub}) 18178Do not remove the tree file (i.e., the snapshot of the compiler internal 18179structures used by @command{gnatstub}) after creating the body stub. 18180 18181@item ^-l^/LINE_LENGTH=^@var{n} 18182@cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub}) 18183Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}} 18184 18185@item ^--no-exception^/NO_EXCEPTION^ 18186@cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub}) 18187Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs. 18188This is not always possible for function stubs. 18189 18190@item ^--no-local-header^/NO_LOCAL_HEADER^ 18191@cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub}) 18192Do not place local comment header with unit name before body stub for a 18193unit. 18194 18195@item ^-o ^/BODY=^@var{body-name} 18196@cindex @option{^-o^/BODY^} (@command{gnatstub}) 18197Body file name. This should be set if the argument file name does not 18198follow 18199the GNAT file naming 18200conventions. If this switch is omitted the default name for the body will be 18201obtained 18202from the argument file name according to the GNAT file naming conventions. 18203 18204@item ^-q^/QUIET^ 18205@cindex @option{^-q^/QUIET^} (@command{gnatstub}) 18206Quiet mode: do not generate a confirmation when a body is 18207successfully created, and do not generate a message when a body is not 18208required for an 18209argument unit. 18210 18211@item ^-r^/TREE_FILE=REUSE^ 18212@cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub}) 18213Reuse the tree file (if it exists) instead of creating it. Instead of 18214creating the tree file for the library unit declaration, @command{gnatstub} 18215tries to find it in the current directory and use it for creating 18216a body. If the tree file is not found, no body is created. This option 18217also implies @option{^-k^/SAVE^}, whether or not 18218the latter is set explicitly. 18219 18220@item ^-t^/TREE_FILE=OVERWRITE^ 18221@cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub}) 18222Overwrite the existing tree file. If the current directory already 18223contains the file which, according to the GNAT file naming rules should 18224be considered as a tree file for the argument source file, 18225@command{gnatstub} 18226will refuse to create the tree file needed to create a sample body 18227unless this option is set. 18228 18229@item ^-v^/VERBOSE^ 18230@cindex @option{^-v^/VERBOSE^} (@command{gnatstub}) 18231Verbose mode: generate version information. 18232 18233@end table 18234 18235@c ********************************* 18236@node Creating Unit Tests Using gnattest 18237@chapter Creating Unit Tests Using @command{gnattest} 18238@findex gnattest 18239 18240@noindent 18241@command{gnattest} is an ASIS-based utility that creates unit-test skeletons 18242as well as a test driver infrastructure (harness). @command{gnattest} creates 18243a skeleton for each visible subprogram in the packages under consideration when 18244they do not exist already. 18245 18246In order to process source files from a project, @command{gnattest} has to 18247semantically analyze the sources. Therefore, test skeletons can only be 18248generated for legal Ada units. If a unit is dependent on other units, 18249those units should be among the source files of the project or of other projects 18250imported by this one. 18251 18252Generated skeletons and harnesses are based on the AUnit testing framework. 18253AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit 18254for Java or CppUnit for C++. While it is advised that gnattest users read 18255the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest. 18256For correct operation of @command{gnattest}, AUnit should be installed and 18257aunit.gpr must be on the project path. This happens automatically when Aunit 18258is installed at its default location. 18259@menu 18260* Running gnattest:: 18261* Switches for gnattest:: 18262* Project Attributes for gnattest:: 18263* Simple Example:: 18264* Setting Up and Tearing Down the Testing Environment:: 18265* Regenerating Tests:: 18266* Default Test Behavior:: 18267* Testing Primitive Operations of Tagged Types:: 18268* Testing Inheritance:: 18269* Tagged Types Substitutability Testing:: 18270* Testing with Contracts:: 18271* Additional Tests:: 18272@ifclear vms 18273* Support for other platforms/run-times:: 18274@end ifclear 18275* Current Limitations:: 18276@end menu 18277 18278@node Running gnattest 18279@section Running @command{gnattest} 18280 18281@noindent 18282@command{gnattest} has a command-line interface of the form 18283 18284@smallexample 18285@c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory} 18286@c Expanding @ovar macro inline (explanation in macro def comments) 18287$ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]} 18288@end smallexample 18289 18290@noindent 18291where 18292@table @var 18293 18294@item -Pprojname 18295specifies the project defining the location of source files. When no 18296file names are provided on the command line, all sources in the project 18297are used as input. This switch is required. 18298 18299@item filename 18300is the name of the source file containing the library unit package declaration 18301for which a test package will be created. The file name may be given with a 18302path. 18303 18304@item @samp{@var{gcc_switches}} 18305is a list of switches for 18306@command{gcc}. These switches will be passed on to all compiler invocations 18307made by @command{gnattest} to generate a set of ASIS trees. Here you can provide 18308@option{^-I^/INCLUDE_DIRS=^} switches to form the source search path, 18309use the @option{-gnatec} switch to set the configuration file, 18310use the @option{-gnat05} switch if sources should be compiled in 18311Ada 2005 mode, etc. 18312 18313@item switches 18314is an optional sequence of switches as described in the next section. 18315 18316@end table 18317 18318@command{gnattest} results can be found in two different places. 18319 18320@itemize @bullet 18321@item automatic harness: 18322the harness code, which is located by default in "gnattest/harness" directory 18323that is created in the object directory of corresponding project file. All of 18324this code is generated completely automatically and can be destroyed and 18325regenerated at will. It is not recommended to modify this code manually, since 18326it could easily be overridden by mistake. The entry point in the harness code is 18327the project file named @command{test_driver.gpr}. Tests can be compiled and run 18328using a command such as: 18329 18330@smallexample 18331gnatmake -P<harness-dir>/test_driver 18332test_runner 18333@end smallexample 18334 18335Note that you might need to specify the necessary values of scenario variables 18336when you are not using the AUnit defaults. 18337 18338@item actual unit test skeletons: 18339a test skeleton for each visible subprogram is created in a separate file, if it 18340doesn't exist already. By default, those separate test files are located in a 18341"gnattest/tests" directory that is created in the object directory of 18342corresponding project file. For example, if a source file my_unit.ads in 18343directory src contains a visible subprogram Proc, then the corresponding unit 18344test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb. 18345<code> is a signature encoding used to differentiate test names in case of 18346overloading. 18347 18348Note that if the project already has both my_unit.ads and my_unit-test_data.ads, 18349this will cause a name conflict with the generated test package. 18350@end itemize 18351 18352@node Switches for gnattest 18353@section Switches for @command{gnattest} 18354 18355@table @option 18356@c !sort! 18357 18358@item --harness-only 18359@cindex @option{--harness-only} (@command{gnattest}) 18360When this option is given, @command{gnattest} creates a harness for all 18361sources, treating them as test packages. 18362 18363@item --additional-tests=@var{projname} 18364@cindex @option{--additional-tests} (@command{gnattest}) 18365Sources described in @var{projname} are considered potential additional 18366manual tests to be added to the test suite. 18367 18368@item -r 18369@cindex @option{-r} (@command{gnattest}) 18370Recursively consider all sources from all projects. 18371 18372@item -X@var{name=value} 18373@cindex @option{-X} (@command{gnattest}) 18374Indicate that external variable @var{name} has the value @var{value}. 18375 18376@item -q 18377@cindex @option{-q} (@command{gnattest}) 18378Suppresses noncritical output messages. 18379 18380@item -v 18381@cindex @option{-v} (@command{gnattest}) 18382Verbose mode: generates version information. 18383 18384@item --validate-type-extensions 18385@cindex @option{--validate-type-extensions} (@command{gnattest}) 18386Enables substitution check: run all tests from all parents in order 18387to check substitutability. 18388 18389@item --skeleton-default=@var{val} 18390@cindex @option{--skeleton-default} (@command{gnattest}) 18391Specifies the default behavior of generated skeletons. @var{val} can be either 18392"fail" or "pass", "fail" being the default. 18393 18394@item --tests-root=@var{dirname} 18395@cindex @option{--tests-root} (@command{gnattest}) 18396The directory hierarchy of tested sources is recreated in the @var{dirname} 18397directory, and test packages are placed in corresponding directories. 18398If the @var{dirname} is a relative path, it is considered relative to the object 18399directory of the project file. When all sources from all projects are taken 18400recursively from all projects, directory hierarchies of tested sources are 18401recreated for each project in their object directories and test packages are 18402placed accordingly. 18403 18404@item --subdir=@var{dirname} 18405@cindex @option{--subdir} (@command{gnattest}) 18406Test packages are placed in subdirectories. 18407 18408@item --tests-dir=@var{dirname} 18409@cindex @option{--tests-dir} (@command{gnattest}) 18410All test packages are placed in the @var{dirname} directory. 18411If the @var{dirname} is a relative path, it is considered relative to the object 18412directory of the project file. When all sources from all projects are taken 18413recursively from all projects, @var{dirname} directories are created for each 18414project in their object directories and test packages are placed accordingly. 18415 18416@item --harness-dir=@var{dirname} 18417@cindex @option{--harness-dir} (@command{gnattest}) 18418specifies the directory that will hold the harness packages and project file 18419for the test driver. If the @var{dirname} is a relative path, it is considered 18420relative to the object directory of the project file. 18421 18422@item --separates 18423@cindex @option{--separates} (@command{gnattest}) 18424Bodies of all test routines are generated as separates. Note that this mode is 18425kept for compatibility reasons only and it is not advised to use it due to 18426possible problems with hash in names of test skeletons when using an 18427inconsistent casing. Separate test skeletons can be incorporated to monolith 18428test package with improved hash being used by using @option{--transition} 18429switch. 18430 18431 18432@item --transition 18433@cindex @option{--transition} (@command{gnattest}) 18434This allows transition from separate test routines to monolith test packages. 18435All matching test routines are overwritten with contents of corresponding 18436separates. Note that if separate test routines had any manually added with 18437clauses they will be moved to the test package body as is and have to be moved 18438by hand. 18439 18440@end table 18441 18442@option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are 18443mutually exclusive. 18444 18445@node Project Attributes for gnattest 18446@section Project Attributes for @command{gnattest} 18447 18448@noindent 18449 18450Most of the command-line options can also be passed to the tool by adding 18451special attributes to the project file. Those attributes should be put in 18452package gnattest. Here is the list of attributes: 18453 18454@itemize @bullet 18455 18456@item Tests_Root 18457is used to select the same output mode as with the --tests-root option. 18458This attribute cannot be used together with Subdir or Tests_Dir. 18459 18460@item Subdir 18461is used to select the same output mode as with the --subdir option. 18462This attribute cannot be used together with Tests_Root or Tests_Dir. 18463 18464@item Tests_Dir 18465is used to select the same output mode as with the --tests-dir option. 18466This attribute cannot be used together with Subdir or Tests_Root. 18467 18468@item Harness_Dir 18469is used to specify the directory in which to place harness packages and project 18470file for the test driver, otherwise specified by --harness-dir. 18471 18472@item Additional_Tests 18473is used to specify the project file, otherwise given by 18474--additional-tests switch. 18475 18476@item Skeletons_Default 18477is used to specify the default behaviour of test skeletons, otherwise 18478specified by --skeleton-default option. The value of this attribute 18479should be either "pass" or "fail". 18480 18481@end itemize 18482 18483Each of those attributes can be overridden from the command line if needed. 18484Other @command{gnattest} switches can also be passed via the project 18485file as an attribute list called GNATtest_Switches. 18486 18487@node Simple Example 18488@section Simple Example 18489 18490@noindent 18491 18492Let's take a very simple example using the first @command{gnattest} example 18493located in: 18494 18495@smallexample 18496<install_prefix>/share/examples/gnattest/simple 18497@end smallexample 18498 18499This project contains a simple package containing one subprogram. By running gnattest: 18500 18501@smallexample 18502$ gnattest --harness-dir=driver -Psimple.gpr 18503@end smallexample 18504 18505a test driver is created in directory "driver". It can be compiled and run: 18506 18507@smallexample 18508$ cd driver 18509$ gprbuild -Ptest_driver 18510$ test_runner 18511@end smallexample 18512 18513One failed test with diagnosis "test not implemented" is reported. 18514Since no special output option was specified, the test package Simple.Tests 18515is located in: 18516 18517@smallexample 18518<install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests 18519@end smallexample 18520 18521For each package containing visible subprograms, a child test package is 18522generated. It contains one test routine per tested subprogram. Each 18523declaration of a test subprogram has a comment specifying which tested 18524subprogram it corresponds to. Bodies of test routines are placed in test package 18525bodies and are surrounded by special comment sections. Those comment sections 18526should not be removed or modified in order for gnattest to be able to regenerate 18527test packages and keep already written tests in place. 18528The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains 18529a single statement: a call to procedure Assert. It has two arguments: 18530the Boolean expression we want to check and the diagnosis message to display if 18531the condition is false. 18532 18533That is where actual testing code should be written after a proper setup. 18534An actual check can be performed by replacing the Assert call with: 18535 18536@smallexample @c ada 18537Assert (Inc (1) = 2, "wrong incrementation"); 18538@end smallexample 18539 18540After recompiling and running the test driver, one successfully passed test 18541is reported. 18542 18543@node Setting Up and Tearing Down the Testing Environment 18544@section Setting Up and Tearing Down the Testing Environment 18545 18546@noindent 18547 18548Besides test routines themselves, each test package has a parent package 18549Test_Data that has two procedures: Set_Up and Tear_Down. This package is never 18550overwritten by the tool. Set_Up is called before each test routine of the 18551package and Tear_Down is called after each test routine. Those two procedures 18552can be used to perform necessary initialization and finalization, 18553memory allocation, etc. Test type declared in Test_Data package is parent type 18554for the test type of test package and can have user-defined components whose 18555values can be set by Set_Up routine and used in test routines afterwards. 18556 18557@node Regenerating Tests 18558@section Regenerating Tests 18559 18560@noindent 18561 18562Bodies of test routines and test_data packages are never overridden after they 18563have been created once. As long as the name of the subprogram, full expanded Ada 18564names, and the order of its parameters is the same, and comment sections are 18565intact the old test routine will fit in its place and no test skeleton will be 18566generated for the subprogram. 18567 18568This can be demonstrated with the previous example. By uncommenting declaration 18569and body of function Dec in simple.ads and simple.adb, running 18570@command{gnattest} on the project, and then running the test driver: 18571 18572@smallexample 18573gnattest --harness-dir=driver -Psimple.gpr 18574cd driver 18575gprbuild -Ptest_driver 18576test_runner 18577@end smallexample 18578 18579the old test is not replaced with a stub, nor is it lost, but a new test 18580skeleton is created for function Dec. 18581 18582The only way of regenerating tests skeletons is to remove the previously created 18583tests together with corresponding comment sections. 18584 18585@node Default Test Behavior 18586@section Default Test Behavior 18587 18588@noindent 18589 18590The generated test driver can treat unimplemented tests in two ways: 18591either count them all as failed (this is useful to see which tests are still 18592left to implement) or as passed (to sort out unimplemented ones from those 18593actually failing). 18594 18595The test driver accepts a switch to specify this behavior: 18596--skeleton-default=val, where val is either "pass" or "fail" (exactly as for 18597@command{gnattest}). 18598 18599The default behavior of the test driver is set with the same switch 18600as passed to gnattest when generating the test driver. 18601 18602Passing it to the driver generated on the first example: 18603 18604@smallexample 18605test_runner --skeleton-default=pass 18606@end smallexample 18607 18608makes both tests pass, even the unimplemented one. 18609 18610@node Testing Primitive Operations of Tagged Types 18611@section Testing Primitive Operations of Tagged Types 18612 18613@noindent 18614 18615Creation of test skeletons for primitive operations of tagged types entails 18616a number of features. Test routines for all primitives of a given tagged type 18617are placed in a separate child package named according to the tagged type. For 18618example, if you have tagged type T in package P, all tests for primitives 18619of T will be in P.T_Test_Data.T_Tests. 18620 18621Consider running gnattest on the second example (note: actual tests for this 18622example already exist, so there's no need to worry if the tool reports that 18623no new stubs were generated): 18624 18625@smallexample 18626cd <install_prefix>/share/examples/gnattest/tagged_rec 18627gnattest --harness-dir=driver -Ptagged_rec.gpr 18628@end smallexample 18629 18630Taking a closer look at the test type declared in the test package 18631Speed1.Controller_Test_Data is necessary. It is declared in: 18632 18633@smallexample 18634<install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests 18635@end smallexample 18636 18637Test types are direct or indirect descendants of 18638AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested 18639subprograms, the user doesn't need to be concerned with them. However, 18640when generating test packages for primitive operations, there are some things 18641the user needs to know. 18642 18643Type Test_Controller has components that allow assignment of various 18644derivations of type Controller. And if you look at the specification of 18645package Speed2.Auto_Controller, you will see that Test_Auto_Controller 18646actually derives from Test_Controller rather than AUnit type Test_Fixture. 18647Thus, test types mirror the hierarchy of tested types. 18648 18649The Set_Up procedure of Test_Data package corresponding to a test package 18650of primitive operations of type T assigns to Fixture a reference to an 18651object of that exact type T. Notice, however, that if the tagged type has 18652discriminants, the Set_Up only has a commented template for setting 18653up the fixture, since filling the discriminant with actual value is up 18654to the user. 18655 18656The knowledge of the structure of test types allows additional testing 18657without additional effort. Those possibilities are described below. 18658 18659@node Testing Inheritance 18660@section Testing Inheritance 18661 18662@noindent 18663 18664Since the test type hierarchy mimics the hierarchy of tested types, the 18665inheritance of tests takes place. An example of such inheritance can be 18666seen by running the test driver generated for the second example. As previously 18667mentioned, actual tests are already written for this example. 18668 18669@smallexample 18670cd driver 18671gprbuild -Ptest_driver 18672test_runner 18673@end smallexample 18674 18675There are 6 passed tests while there are only 5 testable subprograms. The test 18676routine for function Speed has been inherited and run against objects of the 18677derived type. 18678 18679@node Tagged Types Substitutability Testing 18680@section Tagged Types Substitutability Testing 18681 18682@noindent 18683 18684Tagged Types Substitutability Testing is a way of verifying the global type 18685consistency by testing. Global type consistency is a principle stating that if 18686S is a subtype of T (in Ada, S is a derived type of tagged type T), 18687then objects of type T may be replaced with objects of type S (that is, 18688objects of type S may be substituted for objects of type T), without 18689altering any of the desirable properties of the program. When the properties 18690of the program are expressed in the form of subprogram preconditions and 18691postconditions (let's call them pre and post), the principle is formulated as 18692relations between the pre and post of primitive operations and the pre and post 18693of their derived operations. The pre of a derived operation should not be 18694stronger than the original pre, and the post of the derived operation should 18695not be weaker than the original post. Those relations ensure that verifying if 18696a dispatching call is safe can be done just by using the pre and post of the 18697root operation. 18698 18699Verifying global type consistency by testing consists of running all the unit 18700tests associated with the primitives of a given tagged type with objects of its 18701derived types. 18702 18703In the example used in the previous section, there was clearly a violation of 18704type consistency. The overriding primitive Adjust_Speed in package Speed2 18705removes the functionality of the overridden primitive and thus doesn't respect 18706the consistency principle. 18707Gnattest has a special option to run overridden parent tests against objects 18708of the type which have overriding primitives: 18709 18710@smallexample 18711gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr 18712cd driver 18713gprbuild -Ptest_driver 18714test_runner 18715@end smallexample 18716 18717While all the tests pass by themselves, the parent test for Adjust_Speed fails 18718against objects of the derived type. 18719 18720Non-overridden tests are already inherited for derived test types, so the 18721--validate-type-extensions enables the application of overriden tests to objects 18722of derived types. 18723 18724@node Testing with Contracts 18725@section Testing with Contracts 18726 18727@noindent 18728 18729@command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case, 18730as well as corresponding aspects. 18731Test routines are generated, one per each Test_Case associated with a tested 18732subprogram. Those test routines have special wrappers for tested functions 18733that have composition of pre- and postcondition of the subprogram with 18734"requires" and "ensures" of the Test_Case (depending on the mode, pre and post 18735either count for Nominal mode or do not count for Robustness mode). 18736 18737The third example demonstrates how this works: 18738 18739@smallexample 18740cd <install_prefix>/share/examples/gnattest/contracts 18741gnattest --harness-dir=driver -Pcontracts.gpr 18742@end smallexample 18743 18744Putting actual checks within the range of the contract does not cause any 18745error reports. For example, for the test routine which corresponds to 18746test case 1: 18747 18748@smallexample @c ada 18749Assert (Sqrt (9.0) = 3.0, "wrong sqrt"); 18750@end smallexample 18751 18752and for the test routine corresponding to test case 2: 18753 18754@smallexample @c ada 18755Assert (Sqrt (-5.0) = -1.0, "wrong error indication"); 18756@end smallexample 18757 18758are acceptable: 18759 18760@smallexample 18761cd driver 18762gprbuild -Ptest_driver 18763test_runner 18764@end smallexample 18765 18766However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get 18767a precondition violation for test case one. Also, by using any otherwise 18768correct but positive pair of numbers in the second test routine, you can also 18769get a precondition violation. Postconditions are checked and reported 18770the same way. 18771 18772@node Additional Tests 18773@section Additional Tests 18774 18775@noindent 18776@command{gnattest} can add user-written tests to the main suite of the test 18777driver. @command{gnattest} traverses the given packages and searches for test 18778routines. All procedures with a single in out parameter of a type which is 18779derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package 18780specifications are added to the suites and are then executed by the test driver. 18781(Set_Up and Tear_Down are filtered out.) 18782 18783An example illustrates two ways of creating test harnesses for user-written 18784tests. Directory additional_tests contains an AUnit-based test driver written 18785by hand. 18786 18787@smallexample 18788<install_prefix>/share/examples/gnattest/additional_tests/ 18789@end smallexample 18790 18791To create a test driver for already-written tests, use the --harness-only 18792option: 18793 18794@smallexample 18795gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \ 18796 --harness-only 18797gnatmake -Pharness_only/test_driver.gpr 18798harness_only/test_runner 18799@end smallexample 18800 18801Additional tests can also be executed together with generated tests: 18802 18803@smallexample 18804gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \ 18805 --harness-dir=mixing 18806gnatmake -Pmixing/test_driver.gpr 18807mixing/test_runner 18808@end smallexample 18809 18810@ifclear vms 18811@node Support for other platforms/run-times 18812@section Support for other platforms/run-times 18813 18814@noindent 18815@command{gnattest} can be used to generate the test harness for platforms 18816and run-time libraries others than the default native target with the 18817default full run-time. For example, when using a limited run-time library 18818such as Zero FootPrint (ZFP), a simplified harness is generated. 18819 18820Two variables are used to tell the underlying AUnit framework how to generate 18821the test harness: @code{PLATFORM}, which identifies the target, and 18822@code{RUNTIME}, used to determine the run-time library for which the harness 18823is generated. Corresponding prefix should also be used when calling 18824@command{gnattest} for non-native targets. For example, the following options 18825are used to generate the AUnit test harness for a PowerPC ELF target using 18826the ZFP run-time library: 18827 18828@smallexample 18829powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp 18830@end smallexample 18831@end ifclear 18832 18833@node Current Limitations 18834@section Current Limitations 18835 18836@noindent 18837 18838The tool currently does not support following features: 18839 18840@itemize @bullet 18841@item generic tests for generic packages and package instantiations 18842@item tests for protected subprograms and entries 18843 18844@end itemize 18845 18846@c ********************************* 18847@node Performing Dimensionality Analysis in GNAT 18848@chapter Performing Dimensionality Analysis in GNAT 18849@noindent 18850The GNAT compiler now supports dimensionality checking. The user can 18851specify physical units for objects, and the compiler will verify that uses 18852of these objects are compatible with their dimensions, in a fashion that is 18853familiar to engineering practice. The dimensions of algebraic expressions 18854(including powers with static exponents) are computed from their consistuents. 18855 18856This feature depends on Ada 2012 aspect specifications, and is available from 18857version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows 18858the user to define a system of units; the aspect Dimension then allows the user 18859to declare dimensioned quantities within a given system. 18860 18861The major advantage of this model is that it does not require the declaration of 18862multiple operators for all possible combinations of types: it is only necessary 18863to use the proper subtypes in object declarations. 18864 18865The simplest way to impose dimensionality checking on a computation is to make 18866use of the package System.Dim.Mks, which is part of the GNAT library. This 18867package defines a floating-point type MKS_Type, for which a sequence of 18868dimension names are specified, together with their conventional abbreviations. 18869The following should be read together with the full specification of the 18870package, in file s-dimmks.ads. 18871 18872@smallexample @c ada 18873 type Mks_Type is new Long_Long_Float 18874 with 18875 Dimension_System => ( 18876 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'), 18877 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'), 18878 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'), 18879 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'), 18880 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"), 18881 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'), 18882 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J')); 18883@end smallexample 18884 18885@noindent 18886The package then defines a series of subtypes that correspond to these 18887conventional units. For example: 18888@smallexample @c ada 18889 subtype Length is Mks_Type 18890 with 18891 Dimension => (Symbol => 'm', 18892 Meter => 1, 18893 others => 0); 18894@end smallexample 18895@noindent 18896and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature, 18897Amount_Of_Substance, and Luminous_Intensity (the standard set of units of 18898the SI system). 18899 18900The package also defines conventional names for values of each unit, for 18901example: 18902 18903@smallexample @c ada 18904 m : constant Length := 1.0; 18905 kg : constant Mass := 1.0; 18906 s : constant Time := 1.0; 18907 A : constant Electric_Current := 1.0; 18908@end smallexample 18909 18910@noindent 18911as well as useful multiples of these units: 18912 18913@smallexample @c ada 18914 cm : constant Length := 1.0E-02; 18915 g : constant Mass := 1.0E-03; 18916 min : constant Time := 60.0; 18917 day : constant TIme := 60.0 * 24.0 * min; 18918 ... 18919@end smallexample 18920 18921@noindent 18922The user can then define a derived unit by providing the aspect that 18923specifies its dimensions within the MKS system, as well as the string to 18924be used for output of a value of that unit: 18925 18926@smallexample @c ada 18927 subtype Acceleration is Mks_Type 18928 with Dimension => ("m/sec^^^2", Meter => 1, Second => -2, others => 0); 18929@end smallexample 18930 18931@noindent 18932Here is a complete example of use: 18933 18934@smallexample @c ada 18935with System.Dim.MKS; use System.Dim.Mks; 18936with System.Dim.Mks_IO; use System.Dim.Mks_IO; 18937with Text_IO; use Text_IO; 18938procedure Free_Fall is 18939 subtype Acceleration is Mks_Type 18940 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0); 18941 G : constant acceleration := 9.81 * m / (s ** 2); 18942 T : Time := 10.0*s; 18943 Distance : Length; 18944begin 18945 Put ("Gravitational constant: "); 18946 Put (G, Aft => 2, Exp => 0); Put_Line (""); 18947 Distance := 0.5 * G * T ** 2; 18948 Put ("distance travelled in 10 seconds of free fall "); 18949 Put (Distance, Aft => 2, Exp => 0); 18950 Put_Line (""); 18951end Free_Fall; 18952@end smallexample 18953 18954@noindent 18955Execution of this program yields: 18956@smallexample 18957Gravitational constant: 9.81 m/sec^^^2 18958distance travelled in 10 seconds of free fall 490.50 m 18959@end smallexample 18960 18961@noindent 18962However, incorrect assignments such as: 18963 18964@smallexample @c ada 18965 Distance := 5.0; 18966 Distance := 5.0 * kg: 18967@end smallexample 18968 18969@noindent 18970are rejected with the following diagnoses: 18971 18972@smallexample 18973 Distance := 5.0; 18974 >>> dimensions mismatch in assignment 18975 >>> left-hand side has dimension [L] 18976 >>> right-hand side is dimensionless 18977 18978 Distance := 5.0 * kg: 18979 >>> dimensions mismatch in assignment 18980 >>> left-hand side has dimension [L] 18981 >>> right-hand side has dimension [M] 18982@end smallexample 18983 18984@noindent 18985The dimensions of an expression are properly displayed, even if there is 18986no explicit subtype for it. If we add to the program: 18987 18988@smallexample @c ada 18989 Put ("Final velocity: "); 18990 Put (G * T, Aft =>2, Exp =>0); 18991 Put_Line (""); 18992@end smallexample 18993 18994@noindent 18995then the output includes: 18996@smallexample 18997 Final velocity: 98.10 m.s**(-1) 18998@end smallexample 18999 19000@c ********************************* 19001@node Generating Ada Bindings for C and C++ headers 19002@chapter Generating Ada Bindings for C and C++ headers 19003@findex binding 19004 19005@noindent 19006GNAT now comes with a binding generator for C and C++ headers which is 19007intended to do 95% of the tedious work of generating Ada specs from C 19008or C++ header files. 19009 19010Note that this capability is not intended to generate 100% correct Ada specs, 19011and will is some cases require manual adjustments, although it can often 19012be used out of the box in practice. 19013 19014Some of the known limitations include: 19015 19016@itemize @bullet 19017@item only very simple character constant macros are translated into Ada 19018constants. Function macros (macros with arguments) are partially translated 19019as comments, to be completed manually if needed. 19020@item some extensions (e.g. vector types) are not supported 19021@item pointers to pointers or complex structures are mapped to System.Address 19022@item identifiers with identical name (except casing) will generate compilation 19023 errors (e.g. @code{shm_get} vs @code{SHM_GET}). 19024@end itemize 19025 19026The code generated is using the Ada 2005 syntax, which makes it 19027easier to interface with other languages than previous versions of Ada. 19028 19029@menu 19030* Running the binding generator:: 19031* Generating bindings for C++ headers:: 19032* Switches:: 19033@end menu 19034 19035@node Running the binding generator 19036@section Running the binding generator 19037 19038@noindent 19039The binding generator is part of the @command{gcc} compiler and can be 19040invoked via the @option{-fdump-ada-spec} switch, which will generate Ada 19041spec files for the header files specified on the command line, and all 19042header files needed by these files transitively. For example: 19043 19044@smallexample 19045$ g++ -c -fdump-ada-spec -C /usr/include/time.h 19046$ gcc -c -gnat05 *.ads 19047@end smallexample 19048 19049will generate, under GNU/Linux, the following files: @file{time_h.ads}, 19050@file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which 19051correspond to the files @file{/usr/include/time.h}, 19052@file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005 19053mode these Ada specs. 19054 19055The @code{-C} switch tells @command{gcc} to extract comments from headers, 19056and will attempt to generate corresponding Ada comments. 19057 19058If you want to generate a single Ada file and not the transitive closure, you 19059can use instead the @option{-fdump-ada-spec-slim} switch. 19060 19061You can optionally specify a parent unit, of which all generated units will 19062be children, using @code{-fada-spec-parent=}@var{unit}. 19063 19064Note that we recommend when possible to use the @command{g++} driver to 19065generate bindings, even for most C headers, since this will in general 19066generate better Ada specs. For generating bindings for C++ headers, it is 19067mandatory to use the @command{g++} command, or @command{gcc -x c++} which 19068is equivalent in this case. If @command{g++} cannot work on your C headers 19069because of incompatibilities between C and C++, then you can fallback to 19070@command{gcc} instead. 19071 19072For an example of better bindings generated from the C++ front-end, 19073the name of the parameters (when available) are actually ignored by the C 19074front-end. Consider the following C header: 19075 19076@smallexample 19077extern void foo (int variable); 19078@end smallexample 19079 19080with the C front-end, @code{variable} is ignored, and the above is handled as: 19081 19082@smallexample 19083extern void foo (int); 19084@end smallexample 19085 19086generating a generic: 19087 19088@smallexample 19089procedure foo (param1 : int); 19090@end smallexample 19091 19092with the C++ front-end, the name is available, and we generate: 19093 19094@smallexample 19095procedure foo (variable : int); 19096@end smallexample 19097 19098In some cases, the generated bindings will be more complete or more meaningful 19099when defining some macros, which you can do via the @option{-D} switch. This 19100is for example the case with @file{Xlib.h} under GNU/Linux: 19101 19102@smallexample 19103g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h 19104@end smallexample 19105 19106The above will generate more complete bindings than a straight call without 19107the @option{-DXLIB_ILLEGAL_ACCESS} switch. 19108 19109In other cases, it is not possible to parse a header file in a stand-alone 19110manner, because other include files need to be included first. In this 19111case, the solution is to create a small header file including the needed 19112@code{#include} and possible @code{#define} directives. For example, to 19113generate Ada bindings for @file{readline/readline.h}, you need to first 19114include @file{stdio.h}, so you can create a file with the following two 19115lines in e.g. @file{readline1.h}: 19116 19117@smallexample 19118#include <stdio.h> 19119#include <readline/readline.h> 19120@end smallexample 19121 19122and then generate Ada bindings from this file: 19123 19124@smallexample 19125$ g++ -c -fdump-ada-spec readline1.h 19126@end smallexample 19127 19128@node Generating bindings for C++ headers 19129@section Generating bindings for C++ headers 19130 19131@noindent 19132Generating bindings for C++ headers is done using the same options, always 19133with the @command{g++} compiler. 19134 19135In this mode, C++ classes will be mapped to Ada tagged types, constructors 19136will be mapped using the @code{CPP_Constructor} pragma, and when possible, 19137multiple inheritance of abstract classes will be mapped to Ada interfaces 19138(@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional 19139information on interfacing to C++). 19140 19141For example, given the following C++ header file: 19142 19143@smallexample 19144@group 19145@cartouche 19146class Carnivore @{ 19147public: 19148 virtual int Number_Of_Teeth () = 0; 19149@}; 19150 19151class Domestic @{ 19152public: 19153 virtual void Set_Owner (char* Name) = 0; 19154@}; 19155 19156class Animal @{ 19157public: 19158 int Age_Count; 19159 virtual void Set_Age (int New_Age); 19160@}; 19161 19162class Dog : Animal, Carnivore, Domestic @{ 19163 public: 19164 int Tooth_Count; 19165 char *Owner; 19166 19167 virtual int Number_Of_Teeth (); 19168 virtual void Set_Owner (char* Name); 19169 19170 Dog(); 19171@}; 19172@end cartouche 19173@end group 19174@end smallexample 19175 19176The corresponding Ada code is generated: 19177 19178@smallexample @c ada 19179@group 19180@cartouche 19181 package Class_Carnivore is 19182 type Carnivore is limited interface; 19183 pragma Import (CPP, Carnivore); 19184 19185 function Number_Of_Teeth (this : access Carnivore) return int is abstract; 19186 end; 19187 use Class_Carnivore; 19188 19189 package Class_Domestic is 19190 type Domestic is limited interface; 19191 pragma Import (CPP, Domestic); 19192 19193 procedure Set_Owner 19194 (this : access Domestic; 19195 Name : Interfaces.C.Strings.chars_ptr) is abstract; 19196 end; 19197 use Class_Domestic; 19198 19199 package Class_Animal is 19200 type Animal is tagged limited record 19201 Age_Count : aliased int; 19202 end record; 19203 pragma Import (CPP, Animal); 19204 19205 procedure Set_Age (this : access Animal; New_Age : int); 19206 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi"); 19207 end; 19208 use Class_Animal; 19209 19210 package Class_Dog is 19211 type Dog is new Animal and Carnivore and Domestic with record 19212 Tooth_Count : aliased int; 19213 Owner : Interfaces.C.Strings.chars_ptr; 19214 end record; 19215 pragma Import (CPP, Dog); 19216 19217 function Number_Of_Teeth (this : access Dog) return int; 19218 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv"); 19219 19220 procedure Set_Owner 19221 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr); 19222 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc"); 19223 19224 function New_Dog return Dog; 19225 pragma CPP_Constructor (New_Dog); 19226 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev"); 19227 end; 19228 use Class_Dog; 19229@end cartouche 19230@end group 19231@end smallexample 19232 19233@node Switches 19234@section Switches 19235 19236@table @option 19237@item -fdump-ada-spec 19238@cindex @option{-fdump-ada-spec} (@command{gcc}) 19239Generate Ada spec files for the given header files transitively (including 19240all header files that these headers depend upon). 19241 19242@item -fdump-ada-spec-slim 19243@cindex @option{-fdump-ada-spec-slim} (@command{gcc}) 19244Generate Ada spec files for the header files specified on the command line 19245only. 19246 19247@item -fada-spec-parent=@var{unit} 19248@cindex -fada-spec-parent (@command{gcc}) 19249Specifies that all files generated by @option{-fdump-ada-spec*} are 19250to be child units of the specified parent unit. 19251 19252@item -C 19253@cindex @option{-C} (@command{gcc}) 19254Extract comments from headers and generate Ada comments in the Ada spec files. 19255@end table 19256 19257@node Other Utility Programs 19258@chapter Other Utility Programs 19259 19260@noindent 19261This chapter discusses some other utility programs available in the Ada 19262environment. 19263 19264@menu 19265* Using Other Utility Programs with GNAT:: 19266* The External Symbol Naming Scheme of GNAT:: 19267* Converting Ada Files to html with gnathtml:: 19268* Installing gnathtml:: 19269@ifset vms 19270* LSE:: 19271* Profiling:: 19272@end ifset 19273@end menu 19274 19275@node Using Other Utility Programs with GNAT 19276@section Using Other Utility Programs with GNAT 19277 19278@noindent 19279The object files generated by GNAT are in standard system format and in 19280particular the debugging information uses this format. This means 19281programs generated by GNAT can be used with existing utilities that 19282depend on these formats. 19283 19284@ifclear vms 19285In general, any utility program that works with C will also often work with 19286Ada programs generated by GNAT. This includes software utilities such as 19287gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such 19288as Purify. 19289@end ifclear 19290 19291@node The External Symbol Naming Scheme of GNAT 19292@section The External Symbol Naming Scheme of GNAT 19293 19294@noindent 19295In order to interpret the output from GNAT, when using tools that are 19296originally intended for use with other languages, it is useful to 19297understand the conventions used to generate link names from the Ada 19298entity names. 19299 19300All link names are in all lowercase letters. With the exception of library 19301procedure names, the mechanism used is simply to use the full expanded 19302Ada name with dots replaced by double underscores. For example, suppose 19303we have the following package spec: 19304 19305@smallexample @c ada 19306@group 19307@cartouche 19308package QRS is 19309 MN : Integer; 19310end QRS; 19311@end cartouche 19312@end group 19313@end smallexample 19314 19315@noindent 19316The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so 19317the corresponding link name is @code{qrs__mn}. 19318@findex Export 19319Of course if a @code{pragma Export} is used this may be overridden: 19320 19321@smallexample @c ada 19322@group 19323@cartouche 19324package Exports is 19325 Var1 : Integer; 19326 pragma Export (Var1, C, External_Name => "var1_name"); 19327 Var2 : Integer; 19328 pragma Export (Var2, C, Link_Name => "var2_link_name"); 19329end Exports; 19330@end cartouche 19331@end group 19332@end smallexample 19333 19334@noindent 19335In this case, the link name for @var{Var1} is whatever link name the 19336C compiler would assign for the C function @var{var1_name}. This typically 19337would be either @var{var1_name} or @var{_var1_name}, depending on operating 19338system conventions, but other possibilities exist. The link name for 19339@var{Var2} is @var{var2_link_name}, and this is not operating system 19340dependent. 19341 19342@findex _main 19343One exception occurs for library level procedures. A potential ambiguity 19344arises between the required name @code{_main} for the C main program, 19345and the name we would otherwise assign to an Ada library level procedure 19346called @code{Main} (which might well not be the main program). 19347 19348To avoid this ambiguity, we attach the prefix @code{_ada_} to such 19349names. So if we have a library level procedure such as 19350 19351@smallexample @c ada 19352@group 19353@cartouche 19354procedure Hello (S : String); 19355@end cartouche 19356@end group 19357@end smallexample 19358 19359@noindent 19360the external name of this procedure will be @var{_ada_hello}. 19361 19362 19363@node Converting Ada Files to html with gnathtml 19364@section Converting Ada Files to HTML with @code{gnathtml} 19365 19366@noindent 19367This @code{Perl} script allows Ada source files to be browsed using 19368standard Web browsers. For installation procedure, see the section 19369@xref{Installing gnathtml}. 19370 19371Ada reserved keywords are highlighted in a bold font and Ada comments in 19372a blue font. Unless your program was compiled with the gcc @option{-gnatx} 19373switch to suppress the generation of cross-referencing information, user 19374defined variables and types will appear in a different color; you will 19375be able to click on any identifier and go to its declaration. 19376 19377The command line is as follow: 19378@smallexample 19379@c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files} 19380@c Expanding @ovar macro inline (explanation in macro def comments) 19381$ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files} 19382@end smallexample 19383 19384@noindent 19385You can pass it as many Ada files as you want. @code{gnathtml} will generate 19386an html file for every ada file, and a global file called @file{index.htm}. 19387This file is an index of every identifier defined in the files. 19388 19389The available ^switches^options^ are the following ones: 19390 19391@table @option 19392@item -83 19393@cindex @option{-83} (@code{gnathtml}) 19394Only the Ada 83 subset of keywords will be highlighted. 19395 19396@item -cc @var{color} 19397@cindex @option{-cc} (@code{gnathtml}) 19398This option allows you to change the color used for comments. The default 19399value is green. The color argument can be any name accepted by html. 19400 19401@item -d 19402@cindex @option{-d} (@code{gnathtml}) 19403If the Ada files depend on some other files (for instance through 19404@code{with} clauses, the latter files will also be converted to html. 19405Only the files in the user project will be converted to html, not the files 19406in the run-time library itself. 19407 19408@item -D 19409@cindex @option{-D} (@code{gnathtml}) 19410This command is the same as @option{-d} above, but @command{gnathtml} will 19411also look for files in the run-time library, and generate html files for them. 19412 19413@item -ext @var{extension} 19414@cindex @option{-ext} (@code{gnathtml}) 19415This option allows you to change the extension of the generated HTML files. 19416If you do not specify an extension, it will default to @file{htm}. 19417 19418@item -f 19419@cindex @option{-f} (@code{gnathtml}) 19420By default, gnathtml will generate html links only for global entities 19421('with'ed units, global variables and types,@dots{}). If you specify 19422@option{-f} on the command line, then links will be generated for local 19423entities too. 19424 19425@item -l @var{number} 19426@cindex @option{-l} (@code{gnathtml}) 19427If this ^switch^option^ is provided and @var{number} is not 0, then 19428@code{gnathtml} will number the html files every @var{number} line. 19429 19430@item -I @var{dir} 19431@cindex @option{-I} (@code{gnathtml}) 19432Specify a directory to search for library files (@file{.ALI} files) and 19433source files. You can provide several -I switches on the command line, 19434and the directories will be parsed in the order of the command line. 19435 19436@item -o @var{dir} 19437@cindex @option{-o} (@code{gnathtml}) 19438Specify the output directory for html files. By default, gnathtml will 19439saved the generated html files in a subdirectory named @file{html/}. 19440 19441@item -p @var{file} 19442@cindex @option{-p} (@code{gnathtml}) 19443If you are using Emacs and the most recent Emacs Ada mode, which provides 19444a full Integrated Development Environment for compiling, checking, 19445running and debugging applications, you may use @file{.gpr} files 19446to give the directories where Emacs can find sources and object files. 19447 19448Using this ^switch^option^, you can tell gnathtml to use these files. 19449This allows you to get an html version of your application, even if it 19450is spread over multiple directories. 19451 19452@item -sc @var{color} 19453@cindex @option{-sc} (@code{gnathtml}) 19454This ^switch^option^ allows you to change the color used for symbol 19455definitions. 19456The default value is red. The color argument can be any name accepted by html. 19457 19458@item -t @var{file} 19459@cindex @option{-t} (@code{gnathtml}) 19460This ^switch^option^ provides the name of a file. This file contains a list of 19461file names to be converted, and the effect is exactly as though they had 19462appeared explicitly on the command line. This 19463is the recommended way to work around the command line length limit on some 19464systems. 19465 19466@end table 19467 19468@node Installing gnathtml 19469@section Installing @code{gnathtml} 19470 19471@noindent 19472@code{Perl} needs to be installed on your machine to run this script. 19473@code{Perl} is freely available for almost every architecture and 19474Operating System via the Internet. 19475 19476On Unix systems, you may want to modify the first line of the script 19477@code{gnathtml}, to explicitly tell the Operating system where Perl 19478is. The syntax of this line is: 19479@smallexample 19480#!full_path_name_to_perl 19481@end smallexample 19482 19483@noindent 19484Alternatively, you may run the script using the following command line: 19485 19486@smallexample 19487@c $ perl gnathtml.pl @ovar{switches} @var{files} 19488@c Expanding @ovar macro inline (explanation in macro def comments) 19489$ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files} 19490@end smallexample 19491 19492@ifset vms 19493@node LSE 19494@section LSE 19495@findex LSE 19496 19497@noindent 19498The GNAT distribution provides an Ada 95 template for the HP Language 19499Sensitive Editor (LSE), a component of DECset. In order to 19500access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV. 19501 19502@node Profiling 19503@section Profiling 19504@findex PCA 19505 19506@noindent 19507GNAT supports The HP Performance Coverage Analyzer (PCA), a component 19508of DECset. To use it proceed as outlined under ``HELP PCA'', except for running 19509the collection phase with the /DEBUG qualifier. 19510 19511@smallexample 19512$ GNAT MAKE /DEBUG <PROGRAM_NAME> 19513$ DEFINE LIB$DEBUG PCA$COLLECTOR 19514$ RUN/DEBUG <PROGRAM_NAME> 19515@end smallexample 19516@noindent 19517@end ifset 19518 19519@ifclear vms 19520@c ****************************** 19521@node Code Coverage and Profiling 19522@chapter Code Coverage and Profiling 19523@cindex Code Coverage 19524@cindex Profiling 19525 19526@noindent 19527This chapter describes how to use @code{gcov} - coverage testing tool - and 19528@code{gprof} - profiler tool - on your Ada programs. 19529 19530@menu 19531* Code Coverage of Ada Programs using gcov:: 19532* Profiling an Ada Program using gprof:: 19533@end menu 19534 19535@node Code Coverage of Ada Programs using gcov 19536@section Code Coverage of Ada Programs using gcov 19537@cindex gcov 19538@cindex -fprofile-arcs 19539@cindex -ftest-coverage 19540@cindex -coverage 19541@cindex Code Coverage 19542 19543@noindent 19544@code{gcov} is a test coverage program: it analyzes the execution of a given 19545program on selected tests, to help you determine the portions of the program 19546that are still untested. 19547 19548@code{gcov} is part of the GCC suite, and is described in detail in the GCC 19549User's Guide. You can refer to this documentation for a more complete 19550description. 19551 19552This chapter provides a quick startup guide, and 19553details some Gnat-specific features. 19554 19555@menu 19556* Quick startup guide:: 19557* Gnat specifics:: 19558@end menu 19559 19560@node Quick startup guide 19561@subsection Quick startup guide 19562 19563In order to perform coverage analysis of a program using @code{gcov}, 3 19564steps are needed: 19565 19566@itemize @bullet 19567@item 19568Code instrumentation during the compilation process 19569@item 19570Execution of the instrumented program 19571@item 19572Execution of the @code{gcov} tool to generate the result. 19573@end itemize 19574 19575The code instrumentation needed by gcov is created at the object level: 19576The source code is not modified in any way, because the instrumentation code is 19577inserted by gcc during the compilation process. To compile your code with code 19578coverage activated, you need to recompile your whole project using the 19579switches 19580@code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using 19581@code{-fprofile-arcs}. 19582 19583@smallexample 19584$ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \ 19585 -largs -fprofile-arcs 19586@end smallexample 19587 19588This compilation process will create @file{.gcno} files together with 19589the usual object files. 19590 19591Once the program is compiled with coverage instrumentation, you can 19592run it as many times as needed - on portions of a test suite for 19593example. The first execution will produce @file{.gcda} files at the 19594same location as the @file{.gcno} files. The following executions 19595will update those files, so that a cumulative result of the covered 19596portions of the program is generated. 19597 19598Finally, you need to call the @code{gcov} tool. The different options of 19599@code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'. 19600 19601This will create annotated source files with a @file{.gcov} extension: 19602@file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}. 19603 19604@node Gnat specifics 19605@subsection Gnat specifics 19606 19607Because Ada semantics, portions of the source code may be shared among 19608several object files. This is the case for example when generics are 19609involved, when inlining is active or when declarations generate initialisation 19610calls. In order to take 19611into account this shared code, you need to call @code{gcov} on all 19612source files of the tested program at once. 19613 19614The list of source files might exceed the system's maximum command line 19615length. In order to bypass this limitation, a new mechanism has been 19616implemented in @code{gcov}: you can now list all your project's files into a 19617text file, and provide this file to gcov as a parameter, preceded by a @@ 19618(e.g. @samp{gcov @@mysrclist.txt}). 19619 19620Note that on AIX compiling a static library with @code{-fprofile-arcs} is 19621not supported as there can be unresolved symbols during the final link. 19622 19623@node Profiling an Ada Program using gprof 19624@section Profiling an Ada Program using gprof 19625@cindex gprof 19626@cindex -pg 19627@cindex Profiling 19628 19629@noindent 19630This section is not meant to be an exhaustive documentation of @code{gprof}. 19631Full documentation for it can be found in the GNU Profiler User's Guide 19632documentation that is part of this GNAT distribution. 19633 19634Profiling a program helps determine the parts of a program that are executed 19635most often, and are therefore the most time-consuming. 19636 19637@code{gprof} is the standard GNU profiling tool; it has been enhanced to 19638better handle Ada programs and multitasking. 19639It is currently supported on the following platforms 19640@itemize @bullet 19641@item 19642linux x86/x86_64 19643@item 19644solaris sparc/sparc64/x86 19645@item 19646windows x86 19647@end itemize 19648 19649@noindent 19650In order to profile a program using @code{gprof}, 3 steps are needed: 19651 19652@itemize @bullet 19653@item 19654Code instrumentation, requiring a full recompilation of the project with the 19655proper switches. 19656@item 19657Execution of the program under the analysis conditions, i.e. with the desired 19658input. 19659@item 19660Analysis of the results using the @code{gprof} tool. 19661@end itemize 19662 19663@noindent 19664The following sections detail the different steps, and indicate how 19665to interpret the results: 19666@menu 19667* Compilation for profiling:: 19668* Program execution:: 19669* Running gprof:: 19670* Interpretation of profiling results:: 19671@end menu 19672 19673@node Compilation for profiling 19674@subsection Compilation for profiling 19675@cindex -pg 19676@cindex Profiling 19677 19678In order to profile a program the first step is to tell the compiler 19679to generate the necessary profiling information. The compiler switch to be used 19680is @code{-pg}, which must be added to other compilation switches. This 19681switch needs to be specified both during compilation and link stages, and can 19682be specified once when using gnatmake: 19683 19684@smallexample 19685gnatmake -f -pg -P my_project 19686@end smallexample 19687 19688@noindent 19689Note that only the objects that were compiled with the @samp{-pg} switch will 19690be profiled; if you need to profile your whole project, use the @samp{-f} 19691gnatmake switch to force full recompilation. 19692 19693@node Program execution 19694@subsection Program execution 19695 19696@noindent 19697Once the program has been compiled for profiling, you can run it as usual. 19698 19699The only constraint imposed by profiling is that the program must terminate 19700normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be 19701properly analyzed. 19702 19703Once the program completes execution, a data file called @file{gmon.out} is 19704generated in the directory where the program was launched from. If this file 19705already exists, it will be overwritten. 19706 19707@node Running gprof 19708@subsection Running gprof 19709 19710@noindent 19711The @code{gprof} tool is called as follow: 19712 19713@smallexample 19714gprof my_prog gmon.out 19715@end smallexample 19716 19717@noindent 19718or simpler: 19719 19720@smallexample 19721gprof my_prog 19722@end smallexample 19723 19724@noindent 19725The complete form of the gprof command line is the following: 19726 19727@smallexample 19728gprof [^switches^options^] [executable [data-file]] 19729@end smallexample 19730 19731@noindent 19732@code{gprof} supports numerous ^switch^options^. The order of these 19733^switch^options^ does not matter. The full list of options can be found in 19734the GNU Profiler User's Guide documentation that comes with this documentation. 19735 19736The following is the subset of those switches that is most relevant: 19737 19738@table @option 19739 19740@item --demangle[=@var{style}] 19741@itemx --no-demangle 19742@cindex @option{--demangle} (@code{gprof}) 19743These options control whether symbol names should be demangled when 19744printing output. The default is to demangle C++ symbols. The 19745@code{--no-demangle} option may be used to turn off demangling. Different 19746compilers have different mangling styles. The optional demangling style 19747argument can be used to choose an appropriate demangling style for your 19748compiler, in particular Ada symbols generated by GNAT can be demangled using 19749@code{--demangle=gnat}. 19750 19751@item -e @var{function_name} 19752@cindex @option{-e} (@code{gprof}) 19753The @samp{-e @var{function}} option tells @code{gprof} not to print 19754information about the function @var{function_name} (and its 19755children@dots{}) in the call graph. The function will still be listed 19756as a child of any functions that call it, but its index number will be 19757shown as @samp{[not printed]}. More than one @samp{-e} option may be 19758given; only one @var{function_name} may be indicated with each @samp{-e} 19759option. 19760 19761@item -E @var{function_name} 19762@cindex @option{-E} (@code{gprof}) 19763The @code{-E @var{function}} option works like the @code{-e} option, but 19764execution time spent in the function (and children who were not called from 19765anywhere else), will not be used to compute the percentages-of-time for 19766the call graph. More than one @samp{-E} option may be given; only one 19767@var{function_name} may be indicated with each @samp{-E} option. 19768 19769@item -f @var{function_name} 19770@cindex @option{-f} (@code{gprof}) 19771The @samp{-f @var{function}} option causes @code{gprof} to limit the 19772call graph to the function @var{function_name} and its children (and 19773their children@dots{}). More than one @samp{-f} option may be given; 19774only one @var{function_name} may be indicated with each @samp{-f} 19775option. 19776 19777@item -F @var{function_name} 19778@cindex @option{-F} (@code{gprof}) 19779The @samp{-F @var{function}} option works like the @code{-f} option, but 19780only time spent in the function and its children (and their 19781children@dots{}) will be used to determine total-time and 19782percentages-of-time for the call graph. More than one @samp{-F} option 19783may be given; only one @var{function_name} may be indicated with each 19784@samp{-F} option. The @samp{-F} option overrides the @samp{-E} option. 19785 19786@end table 19787 19788@node Interpretation of profiling results 19789@subsection Interpretation of profiling results 19790 19791@noindent 19792 19793The results of the profiling analysis are represented by two arrays: the 19794'flat profile' and the 'call graph'. Full documentation of those outputs 19795can be found in the GNU Profiler User's Guide. 19796 19797The flat profile shows the time spent in each function of the program, and how 19798many time it has been called. This allows you to locate easily the most 19799time-consuming functions. 19800 19801The call graph shows, for each subprogram, the subprograms that call it, 19802and the subprograms that it calls. It also provides an estimate of the time 19803spent in each of those callers/called subprograms. 19804@end ifclear 19805 19806@c ****************************** 19807@node Running and Debugging Ada Programs 19808@chapter Running and Debugging Ada Programs 19809@cindex Debugging 19810 19811@noindent 19812This chapter discusses how to debug Ada programs. 19813@ifset vms 19814It applies to GNAT on the Alpha OpenVMS platform; 19815for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual}, 19816since HP has implemented Ada support in the OpenVMS debugger on I64. 19817@end ifset 19818 19819An incorrect Ada program may be handled in three ways by the GNAT compiler: 19820 19821@enumerate 19822@item 19823The illegality may be a violation of the static semantics of Ada. In 19824that case GNAT diagnoses the constructs in the program that are illegal. 19825It is then a straightforward matter for the user to modify those parts of 19826the program. 19827 19828@item 19829The illegality may be a violation of the dynamic semantics of Ada. In 19830that case the program compiles and executes, but may generate incorrect 19831results, or may terminate abnormally with some exception. 19832 19833@item 19834When presented with a program that contains convoluted errors, GNAT 19835itself may terminate abnormally without providing full diagnostics on 19836the incorrect user program. 19837@end enumerate 19838 19839@menu 19840* The GNAT Debugger GDB:: 19841* Running GDB:: 19842* Introduction to GDB Commands:: 19843* Using Ada Expressions:: 19844* Calling User-Defined Subprograms:: 19845* Using the Next Command in a Function:: 19846* Ada Exceptions:: 19847* Ada Tasks:: 19848* Debugging Generic Units:: 19849* Remote Debugging using gdbserver:: 19850* GNAT Abnormal Termination or Failure to Terminate:: 19851* Naming Conventions for GNAT Source Files:: 19852* Getting Internal Debugging Information:: 19853* Stack Traceback:: 19854@end menu 19855 19856@cindex Debugger 19857@findex gdb 19858 19859@node The GNAT Debugger GDB 19860@section The GNAT Debugger GDB 19861 19862@noindent 19863@code{GDB} is a general purpose, platform-independent debugger that 19864can be used to debug mixed-language programs compiled with @command{gcc}, 19865and in particular is capable of debugging Ada programs compiled with 19866GNAT. The latest versions of @code{GDB} are Ada-aware and can handle 19867complex Ada data structures. 19868 19869@xref{Top,, Debugging with GDB, gdb, Debugging with GDB}, 19870@ifset vms 19871located in the GNU:[DOCS] directory, 19872@end ifset 19873for full details on the usage of @code{GDB}, including a section on 19874its usage on programs. This manual should be consulted for full 19875details. The section that follows is a brief introduction to the 19876philosophy and use of @code{GDB}. 19877 19878When GNAT programs are compiled, the compiler optionally writes debugging 19879information into the generated object file, including information on 19880line numbers, and on declared types and variables. This information is 19881separate from the generated code. It makes the object files considerably 19882larger, but it does not add to the size of the actual executable that 19883will be loaded into memory, and has no impact on run-time performance. The 19884generation of debug information is triggered by the use of the 19885^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command 19886used to carry out the compilations. It is important to emphasize that 19887the use of these options does not change the generated code. 19888 19889The debugging information is written in standard system formats that 19890are used by many tools, including debuggers and profilers. The format 19891of the information is typically designed to describe C types and 19892semantics, but GNAT implements a translation scheme which allows full 19893details about Ada types and variables to be encoded into these 19894standard C formats. Details of this encoding scheme may be found in 19895the file exp_dbug.ads in the GNAT source distribution. However, the 19896details of this encoding are, in general, of no interest to a user, 19897since @code{GDB} automatically performs the necessary decoding. 19898 19899When a program is bound and linked, the debugging information is 19900collected from the object files, and stored in the executable image of 19901the program. Again, this process significantly increases the size of 19902the generated executable file, but it does not increase the size of 19903the executable program itself. Furthermore, if this program is run in 19904the normal manner, it runs exactly as if the debug information were 19905not present, and takes no more actual memory. 19906 19907However, if the program is run under control of @code{GDB}, the 19908debugger is activated. The image of the program is loaded, at which 19909point it is ready to run. If a run command is given, then the program 19910will run exactly as it would have if @code{GDB} were not present. This 19911is a crucial part of the @code{GDB} design philosophy. @code{GDB} is 19912entirely non-intrusive until a breakpoint is encountered. If no 19913breakpoint is ever hit, the program will run exactly as it would if no 19914debugger were present. When a breakpoint is hit, @code{GDB} accesses 19915the debugging information and can respond to user commands to inspect 19916variables, and more generally to report on the state of execution. 19917 19918@c ************** 19919@node Running GDB 19920@section Running GDB 19921 19922@noindent 19923This section describes how to initiate the debugger. 19924@c The above sentence is really just filler, but it was otherwise 19925@c clumsy to get the first paragraph nonindented given the conditional 19926@c nature of the description 19927 19928@ifclear vms 19929The debugger can be launched from a @code{GPS} menu or 19930directly from the command line. The description below covers the latter use. 19931All the commands shown can be used in the @code{GPS} debug console window, 19932but there are usually more GUI-based ways to achieve the same effect. 19933@end ifclear 19934 19935The command to run @code{GDB} is 19936 19937@smallexample 19938$ ^gdb program^GDB PROGRAM^ 19939@end smallexample 19940 19941@noindent 19942where @code{^program^PROGRAM^} is the name of the executable file. This 19943activates the debugger and results in a prompt for debugger commands. 19944The simplest command is simply @code{run}, which causes the program to run 19945exactly as if the debugger were not present. The following section 19946describes some of the additional commands that can be given to @code{GDB}. 19947 19948@c ******************************* 19949@node Introduction to GDB Commands 19950@section Introduction to GDB Commands 19951 19952@noindent 19953@code{GDB} contains a large repertoire of commands. @xref{Top,, 19954Debugging with GDB, gdb, Debugging with GDB}, 19955@ifset vms 19956located in the GNU:[DOCS] directory, 19957@end ifset 19958for extensive documentation on the use 19959of these commands, together with examples of their use. Furthermore, 19960the command @command{help} invoked from within GDB activates a simple help 19961facility which summarizes the available commands and their options. 19962In this section we summarize a few of the most commonly 19963used commands to give an idea of what @code{GDB} is about. You should create 19964a simple program with debugging information and experiment with the use of 19965these @code{GDB} commands on the program as you read through the 19966following section. 19967 19968@table @code 19969@item set args @var{arguments} 19970The @var{arguments} list above is a list of arguments to be passed to 19971the program on a subsequent run command, just as though the arguments 19972had been entered on a normal invocation of the program. The @code{set args} 19973command is not needed if the program does not require arguments. 19974 19975@item run 19976The @code{run} command causes execution of the program to start from 19977the beginning. If the program is already running, that is to say if 19978you are currently positioned at a breakpoint, then a prompt will ask 19979for confirmation that you want to abandon the current execution and 19980restart. 19981 19982@item breakpoint @var{location} 19983The breakpoint command sets a breakpoint, that is to say a point at which 19984execution will halt and @code{GDB} will await further 19985commands. @var{location} is 19986either a line number within a file, given in the format @code{file:linenumber}, 19987or it is the name of a subprogram. If you request that a breakpoint be set on 19988a subprogram that is overloaded, a prompt will ask you to specify on which of 19989those subprograms you want to breakpoint. You can also 19990specify that all of them should be breakpointed. If the program is run 19991and execution encounters the breakpoint, then the program 19992stops and @code{GDB} signals that the breakpoint was encountered by 19993printing the line of code before which the program is halted. 19994 19995@item catch exception @var{name} 19996This command causes the program execution to stop whenever exception 19997@var{name} is raised. If @var{name} is omitted, then the execution is 19998suspended when any exception is raised. 19999 20000@item print @var{expression} 20001This will print the value of the given expression. Most simple 20002Ada expression formats are properly handled by @code{GDB}, so the expression 20003can contain function calls, variables, operators, and attribute references. 20004 20005@item continue 20006Continues execution following a breakpoint, until the next breakpoint or the 20007termination of the program. 20008 20009@item step 20010Executes a single line after a breakpoint. If the next statement 20011is a subprogram call, execution continues into (the first statement of) 20012the called subprogram. 20013 20014@item next 20015Executes a single line. If this line is a subprogram call, executes and 20016returns from the call. 20017 20018@item list 20019Lists a few lines around the current source location. In practice, it 20020is usually more convenient to have a separate edit window open with the 20021relevant source file displayed. Successive applications of this command 20022print subsequent lines. The command can be given an argument which is a 20023line number, in which case it displays a few lines around the specified one. 20024 20025@item backtrace 20026Displays a backtrace of the call chain. This command is typically 20027used after a breakpoint has occurred, to examine the sequence of calls that 20028leads to the current breakpoint. The display includes one line for each 20029activation record (frame) corresponding to an active subprogram. 20030 20031@item up 20032At a breakpoint, @code{GDB} can display the values of variables local 20033to the current frame. The command @code{up} can be used to 20034examine the contents of other active frames, by moving the focus up 20035the stack, that is to say from callee to caller, one frame at a time. 20036 20037@item down 20038Moves the focus of @code{GDB} down from the frame currently being 20039examined to the frame of its callee (the reverse of the previous command), 20040 20041@item frame @var{n} 20042Inspect the frame with the given number. The value 0 denotes the frame 20043of the current breakpoint, that is to say the top of the call stack. 20044 20045@end table 20046 20047@noindent 20048The above list is a very short introduction to the commands that 20049@code{GDB} provides. Important additional capabilities, including conditional 20050breakpoints, the ability to execute command sequences on a breakpoint, 20051the ability to debug at the machine instruction level and many other 20052features are described in detail in @ref{Top,, Debugging with GDB, gdb, 20053Debugging with GDB}. Note that most commands can be abbreviated 20054(for example, c for continue, bt for backtrace). 20055 20056@node Using Ada Expressions 20057@section Using Ada Expressions 20058@cindex Ada expressions 20059 20060@noindent 20061@code{GDB} supports a fairly large subset of Ada expression syntax, with some 20062extensions. The philosophy behind the design of this subset is 20063 20064@itemize @bullet 20065@item 20066That @code{GDB} should provide basic literals and access to operations for 20067arithmetic, dereferencing, field selection, indexing, and subprogram calls, 20068leaving more sophisticated computations to subprograms written into the 20069program (which therefore may be called from @code{GDB}). 20070 20071@item 20072That type safety and strict adherence to Ada language restrictions 20073are not particularly important to the @code{GDB} user. 20074 20075@item 20076That brevity is important to the @code{GDB} user. 20077@end itemize 20078 20079@noindent 20080Thus, for brevity, the debugger acts as if there were 20081implicit @code{with} and @code{use} clauses in effect for all user-written 20082packages, thus making it unnecessary to fully qualify most names with 20083their packages, regardless of context. Where this causes ambiguity, 20084@code{GDB} asks the user's intent. 20085 20086For details on the supported Ada syntax, see @ref{Top,, Debugging with 20087GDB, gdb, Debugging with GDB}. 20088 20089@node Calling User-Defined Subprograms 20090@section Calling User-Defined Subprograms 20091 20092@noindent 20093An important capability of @code{GDB} is the ability to call user-defined 20094subprograms while debugging. This is achieved simply by entering 20095a subprogram call statement in the form: 20096 20097@smallexample 20098call subprogram-name (parameters) 20099@end smallexample 20100 20101@noindent 20102The keyword @code{call} can be omitted in the normal case where the 20103@code{subprogram-name} does not coincide with any of the predefined 20104@code{GDB} commands. 20105 20106The effect is to invoke the given subprogram, passing it the 20107list of parameters that is supplied. The parameters can be expressions and 20108can include variables from the program being debugged. The 20109subprogram must be defined 20110at the library level within your program, and @code{GDB} will call the 20111subprogram within the environment of your program execution (which 20112means that the subprogram is free to access or even modify variables 20113within your program). 20114 20115The most important use of this facility is in allowing the inclusion of 20116debugging routines that are tailored to particular data structures 20117in your program. Such debugging routines can be written to provide a suitably 20118high-level description of an abstract type, rather than a low-level dump 20119of its physical layout. After all, the standard 20120@code{GDB print} command only knows the physical layout of your 20121types, not their abstract meaning. Debugging routines can provide information 20122at the desired semantic level and are thus enormously useful. 20123 20124For example, when debugging GNAT itself, it is crucial to have access to 20125the contents of the tree nodes used to represent the program internally. 20126But tree nodes are represented simply by an integer value (which in turn 20127is an index into a table of nodes). 20128Using the @code{print} command on a tree node would simply print this integer 20129value, which is not very useful. But the PN routine (defined in file 20130treepr.adb in the GNAT sources) takes a tree node as input, and displays 20131a useful high level representation of the tree node, which includes the 20132syntactic category of the node, its position in the source, the integers 20133that denote descendant nodes and parent node, as well as varied 20134semantic information. To study this example in more detail, you might want to 20135look at the body of the PN procedure in the stated file. 20136 20137@node Using the Next Command in a Function 20138@section Using the Next Command in a Function 20139 20140@noindent 20141When you use the @code{next} command in a function, the current source 20142location will advance to the next statement as usual. A special case 20143arises in the case of a @code{return} statement. 20144 20145Part of the code for a return statement is the ``epilog'' of the function. 20146This is the code that returns to the caller. There is only one copy of 20147this epilog code, and it is typically associated with the last return 20148statement in the function if there is more than one return. In some 20149implementations, this epilog is associated with the first statement 20150of the function. 20151 20152The result is that if you use the @code{next} command from a return 20153statement that is not the last return statement of the function you 20154may see a strange apparent jump to the last return statement or to 20155the start of the function. You should simply ignore this odd jump. 20156The value returned is always that from the first return statement 20157that was stepped through. 20158 20159@node Ada Exceptions 20160@section Stopping when Ada Exceptions are Raised 20161@cindex Exceptions 20162 20163@noindent 20164You can set catchpoints that stop the program execution when your program 20165raises selected exceptions. 20166 20167@table @code 20168@item catch exception 20169Set a catchpoint that stops execution whenever (any task in the) program 20170raises any exception. 20171 20172@item catch exception @var{name} 20173Set a catchpoint that stops execution whenever (any task in the) program 20174raises the exception @var{name}. 20175 20176@item catch exception unhandled 20177Set a catchpoint that stops executing whenever (any task in the) program 20178raises an exception for which there is no handler. 20179 20180@item info exceptions 20181@itemx info exceptions @var{regexp} 20182The @code{info exceptions} command permits the user to examine all defined 20183exceptions within Ada programs. With a regular expression, @var{regexp}, as 20184argument, prints out only those exceptions whose name matches @var{regexp}. 20185@end table 20186 20187@node Ada Tasks 20188@section Ada Tasks 20189@cindex Tasks 20190 20191@noindent 20192@code{GDB} allows the following task-related commands: 20193 20194@table @code 20195@item info tasks 20196This command shows a list of current Ada tasks, as in the following example: 20197 20198@smallexample 20199@iftex 20200@leftskip=0cm 20201@end iftex 20202(gdb) info tasks 20203 ID TID P-ID Thread Pri State Name 20204 1 8088000 0 807e000 15 Child Activation Wait main_task 20205 2 80a4000 1 80ae000 15 Accept/Select Wait b 20206 3 809a800 1 80a4800 15 Child Activation Wait a 20207* 4 80ae800 3 80b8000 15 Running c 20208@end smallexample 20209 20210@noindent 20211In this listing, the asterisk before the first task indicates it to be the 20212currently running task. The first column lists the task ID that is used 20213to refer to tasks in the following commands. 20214 20215@item break @var{linespec} task @var{taskid} 20216@itemx break @var{linespec} task @var{taskid} if @dots{} 20217@cindex Breakpoints and tasks 20218These commands are like the @code{break @dots{} thread @dots{}}. 20219@var{linespec} specifies source lines. 20220 20221Use the qualifier @samp{task @var{taskid}} with a breakpoint command 20222to specify that you only want @code{GDB} to stop the program when a 20223particular Ada task reaches this breakpoint. @var{taskid} is one of the 20224numeric task identifiers assigned by @code{GDB}, shown in the first 20225column of the @samp{info tasks} display. 20226 20227If you do not specify @samp{task @var{taskid}} when you set a 20228breakpoint, the breakpoint applies to @emph{all} tasks of your 20229program. 20230 20231You can use the @code{task} qualifier on conditional breakpoints as 20232well; in this case, place @samp{task @var{taskid}} before the 20233breakpoint condition (before the @code{if}). 20234 20235@item task @var{taskno} 20236@cindex Task switching 20237 20238This command allows to switch to the task referred by @var{taskno}. In 20239particular, This allows to browse the backtrace of the specified 20240task. It is advised to switch back to the original task before 20241continuing execution otherwise the scheduling of the program may be 20242perturbed. 20243@end table 20244 20245@noindent 20246For more detailed information on the tasking support, 20247see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}. 20248 20249@node Debugging Generic Units 20250@section Debugging Generic Units 20251@cindex Debugging Generic Units 20252@cindex Generics 20253 20254@noindent 20255GNAT always uses code expansion for generic instantiation. This means that 20256each time an instantiation occurs, a complete copy of the original code is 20257made, with appropriate substitutions of formals by actuals. 20258 20259It is not possible to refer to the original generic entities in 20260@code{GDB}, but it is always possible to debug a particular instance of 20261a generic, by using the appropriate expanded names. For example, if we have 20262 20263@smallexample @c ada 20264@group 20265@cartouche 20266procedure g is 20267 20268 generic package k is 20269 procedure kp (v1 : in out integer); 20270 end k; 20271 20272 package body k is 20273 procedure kp (v1 : in out integer) is 20274 begin 20275 v1 := v1 + 1; 20276 end kp; 20277 end k; 20278 20279 package k1 is new k; 20280 package k2 is new k; 20281 20282 var : integer := 1; 20283 20284begin 20285 k1.kp (var); 20286 k2.kp (var); 20287 k1.kp (var); 20288 k2.kp (var); 20289end; 20290@end cartouche 20291@end group 20292@end smallexample 20293 20294@noindent 20295Then to break on a call to procedure kp in the k2 instance, simply 20296use the command: 20297 20298@smallexample 20299(gdb) break g.k2.kp 20300@end smallexample 20301 20302@noindent 20303When the breakpoint occurs, you can step through the code of the 20304instance in the normal manner and examine the values of local variables, as for 20305other units. 20306 20307@node Remote Debugging using gdbserver 20308@section Remote Debugging using gdbserver 20309@cindex Remote Debugging using gdbserver 20310 20311@noindent 20312On platforms where gdbserver is supported, it is possible to use this tool 20313to debug your application remotely. This can be useful in situations 20314where the program needs to be run on a target host that is different 20315from the host used for development, particularly when the target has 20316a limited amount of resources (either CPU and/or memory). 20317 20318To do so, start your program using gdbserver on the target machine. 20319gdbserver then automatically suspends the execution of your program 20320at its entry point, waiting for a debugger to connect to it. The 20321following commands starts an application and tells gdbserver to 20322wait for a connection with the debugger on localhost port 4444. 20323 20324@smallexample 20325$ gdbserver localhost:4444 program 20326Process program created; pid = 5685 20327Listening on port 4444 20328@end smallexample 20329 20330Once gdbserver has started listening, we can tell the debugger to establish 20331a connection with this gdbserver, and then start the same debugging session 20332as if the program was being debugged on the same host, directly under 20333the control of GDB. 20334 20335@smallexample 20336$ gdb program 20337(gdb) target remote targethost:4444 20338Remote debugging using targethost:4444 203390x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so. 20340(gdb) b foo.adb:3 20341Breakpoint 1 at 0x401f0c: file foo.adb, line 3. 20342(gdb) continue 20343Continuing. 20344 20345Breakpoint 1, foo () at foo.adb:4 203464 end foo; 20347@end smallexample 20348 20349It is also possible to use gdbserver to attach to an already running 20350program, in which case the execution of that program is simply suspended 20351until the connection between the debugger and gdbserver is established. 20352 20353For more information on how to use gdbserver, @ref{Top, Server, Using 20354the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support 20355for gdbserver on x86-linux, x86-windows and x86_64-linux. 20356 20357@node GNAT Abnormal Termination or Failure to Terminate 20358@section GNAT Abnormal Termination or Failure to Terminate 20359@cindex GNAT Abnormal Termination or Failure to Terminate 20360 20361@noindent 20362When presented with programs that contain serious errors in syntax 20363or semantics, 20364GNAT may on rare occasions experience problems in operation, such 20365as aborting with a 20366segmentation fault or illegal memory access, raising an internal 20367exception, terminating abnormally, or failing to terminate at all. 20368In such cases, you can activate 20369various features of GNAT that can help you pinpoint the construct in your 20370program that is the likely source of the problem. 20371 20372The following strategies are presented in increasing order of 20373difficulty, corresponding to your experience in using GNAT and your 20374familiarity with compiler internals. 20375 20376@enumerate 20377@item 20378Run @command{gcc} with the @option{-gnatf}. This first 20379switch causes all errors on a given line to be reported. In its absence, 20380only the first error on a line is displayed. 20381 20382The @option{-gnatdO} switch causes errors to be displayed as soon as they 20383are encountered, rather than after compilation is terminated. If GNAT 20384terminates prematurely or goes into an infinite loop, the last error 20385message displayed may help to pinpoint the culprit. 20386 20387@item 20388Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this 20389mode, @command{gcc} produces ongoing information about the progress of the 20390compilation and provides the name of each procedure as code is 20391generated. This switch allows you to find which Ada procedure was being 20392compiled when it encountered a code generation problem. 20393 20394@item 20395@cindex @option{-gnatdc} switch 20396Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific 20397switch that does for the front-end what @option{^-v^VERBOSE^} does 20398for the back end. The system prints the name of each unit, 20399either a compilation unit or nested unit, as it is being analyzed. 20400@item 20401Finally, you can start 20402@code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the 20403front-end of GNAT, and can be run independently (normally it is just 20404called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you 20405would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The 20406@code{where} command is the first line of attack; the variable 20407@code{lineno} (seen by @code{print lineno}), used by the second phase of 20408@code{gnat1} and by the @command{gcc} backend, indicates the source line at 20409which the execution stopped, and @code{input_file name} indicates the name of 20410the source file. 20411@end enumerate 20412 20413@node Naming Conventions for GNAT Source Files 20414@section Naming Conventions for GNAT Source Files 20415 20416@noindent 20417In order to examine the workings of the GNAT system, the following 20418brief description of its organization may be helpful: 20419 20420@itemize @bullet 20421@item 20422Files with prefix @file{^sc^SC^} contain the lexical scanner. 20423 20424@item 20425All files prefixed with @file{^par^PAR^} are components of the parser. The 20426numbers correspond to chapters of the Ada Reference Manual. For example, 20427parsing of select statements can be found in @file{par-ch9.adb}. 20428 20429@item 20430All files prefixed with @file{^sem^SEM^} perform semantic analysis. The 20431numbers correspond to chapters of the Ada standard. For example, all 20432issues involving context clauses can be found in @file{sem_ch10.adb}. In 20433addition, some features of the language require sufficient special processing 20434to justify their own semantic files: sem_aggr for aggregates, sem_disp for 20435dynamic dispatching, etc. 20436 20437@item 20438All files prefixed with @file{^exp^EXP^} perform normalization and 20439expansion of the intermediate representation (abstract syntax tree, or AST). 20440these files use the same numbering scheme as the parser and semantics files. 20441For example, the construction of record initialization procedures is done in 20442@file{exp_ch3.adb}. 20443 20444@item 20445The files prefixed with @file{^bind^BIND^} implement the binder, which 20446verifies the consistency of the compilation, determines an order of 20447elaboration, and generates the bind file. 20448 20449@item 20450The files @file{atree.ads} and @file{atree.adb} detail the low-level 20451data structures used by the front-end. 20452 20453@item 20454The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of 20455the abstract syntax tree as produced by the parser. 20456 20457@item 20458The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of 20459all entities, computed during semantic analysis. 20460 20461@item 20462Library management issues are dealt with in files with prefix 20463@file{^lib^LIB^}. 20464 20465@item 20466@findex Ada 20467@cindex Annex A 20468Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as 20469defined in Annex A. 20470 20471@item 20472@findex Interfaces 20473@cindex Annex B 20474Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as 20475defined in Annex B. 20476 20477@item 20478@findex System 20479Files with prefix @file{^s-^S-^} are children of @code{System}. This includes 20480both language-defined children and GNAT run-time routines. 20481 20482@item 20483@findex GNAT 20484Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful 20485general-purpose packages, fully documented in their specs. All 20486the other @file{.c} files are modifications of common @command{gcc} files. 20487@end itemize 20488 20489@node Getting Internal Debugging Information 20490@section Getting Internal Debugging Information 20491 20492@noindent 20493Most compilers have internal debugging switches and modes. GNAT 20494does also, except GNAT internal debugging switches and modes are not 20495secret. A summary and full description of all the compiler and binder 20496debug flags are in the file @file{debug.adb}. You must obtain the 20497sources of the compiler to see the full detailed effects of these flags. 20498 20499The switches that print the source of the program (reconstructed from 20500the internal tree) are of general interest for user programs, as are the 20501options to print 20502the full internal tree, and the entity table (the symbol table 20503information). The reconstructed source provides a readable version of the 20504program after the front-end has completed analysis and expansion, 20505and is useful when studying the performance of specific constructs. 20506For example, constraint checks are indicated, complex aggregates 20507are replaced with loops and assignments, and tasking primitives 20508are replaced with run-time calls. 20509 20510@node Stack Traceback 20511@section Stack Traceback 20512@cindex traceback 20513@cindex stack traceback 20514@cindex stack unwinding 20515 20516@noindent 20517Traceback is a mechanism to display the sequence of subprogram calls that 20518leads to a specified execution point in a program. Often (but not always) 20519the execution point is an instruction at which an exception has been raised. 20520This mechanism is also known as @i{stack unwinding} because it obtains 20521its information by scanning the run-time stack and recovering the activation 20522records of all active subprograms. Stack unwinding is one of the most 20523important tools for program debugging. 20524 20525The first entry stored in traceback corresponds to the deepest calling level, 20526that is to say the subprogram currently executing the instruction 20527from which we want to obtain the traceback. 20528 20529Note that there is no runtime performance penalty when stack traceback 20530is enabled, and no exception is raised during program execution. 20531 20532@menu 20533* Non-Symbolic Traceback:: 20534* Symbolic Traceback:: 20535@end menu 20536 20537@node Non-Symbolic Traceback 20538@subsection Non-Symbolic Traceback 20539@cindex traceback, non-symbolic 20540 20541@noindent 20542Note: this feature is not supported on all platforms. See 20543@file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported 20544platforms. 20545 20546@menu 20547* Tracebacks From an Unhandled Exception:: 20548* Tracebacks From Exception Occurrences (non-symbolic):: 20549* Tracebacks From Anywhere in a Program (non-symbolic):: 20550@end menu 20551 20552@node Tracebacks From an Unhandled Exception 20553@subsubsection Tracebacks From an Unhandled Exception 20554 20555@noindent 20556A runtime non-symbolic traceback is a list of addresses of call instructions. 20557To enable this feature you must use the @option{-E} 20558@code{gnatbind}'s option. With this option a stack traceback is stored as part 20559of exception information. You can retrieve this information using the 20560@code{addr2line} tool. 20561 20562Here is a simple example: 20563 20564@smallexample @c ada 20565@cartouche 20566procedure STB is 20567 20568 procedure P1 is 20569 begin 20570 raise Constraint_Error; 20571 end P1; 20572 20573 procedure P2 is 20574 begin 20575 P1; 20576 end P2; 20577 20578begin 20579 P2; 20580end STB; 20581@end cartouche 20582@end smallexample 20583 20584@smallexample 20585$ gnatmake stb -bargs -E 20586$ stb 20587 20588Execution terminated by unhandled exception 20589Exception name: CONSTRAINT_ERROR 20590Message: stb.adb:5 20591Call stack traceback locations: 205920x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 20593@end smallexample 20594 20595@noindent 20596As we see the traceback lists a sequence of addresses for the unhandled 20597exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to 20598guess that this exception come from procedure P1. To translate these 20599addresses into the source lines where the calls appear, the 20600@code{addr2line} tool, described below, is invaluable. The use of this tool 20601requires the program to be compiled with debug information. 20602 20603@smallexample 20604$ gnatmake -g stb -bargs -E 20605$ stb 20606 20607Execution terminated by unhandled exception 20608Exception name: CONSTRAINT_ERROR 20609Message: stb.adb:5 20610Call stack traceback locations: 206110x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4 20612 20613$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 20614 0x4011f1 0x77e892a4 20615 2061600401373 at d:/stb/stb.adb:5 206170040138B at d:/stb/stb.adb:10 206180040139C at d:/stb/stb.adb:14 2061900401335 at d:/stb/b~stb.adb:104 20620004011C4 at /build/@dots{}/crt1.c:200 20621004011F1 at /build/@dots{}/crt1.c:222 2062277E892A4 in ?? at ??:0 20623@end smallexample 20624 20625@noindent 20626The @code{addr2line} tool has several other useful options: 20627 20628@table @code 20629@item --functions 20630to get the function name corresponding to any location 20631 20632@item --demangle=gnat 20633to use the gnat decoding mode for the function names. Note that 20634for binutils version 2.9.x the option is simply @option{--demangle}. 20635@end table 20636 20637@smallexample 20638$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b 20639 0x40139c 0x401335 0x4011c4 0x4011f1 20640 2064100401373 in stb.p1 at d:/stb/stb.adb:5 206420040138B in stb.p2 at d:/stb/stb.adb:10 206430040139C in stb at d:/stb/stb.adb:14 2064400401335 in main at d:/stb/b~stb.adb:104 20645004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200 20646004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222 20647@end smallexample 20648 20649@noindent 20650From this traceback we can see that the exception was raised in 20651@file{stb.adb} at line 5, which was reached from a procedure call in 20652@file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file, 20653which contains the call to the main program. 20654@xref{Running gnatbind}. The remaining entries are assorted runtime routines, 20655and the output will vary from platform to platform. 20656 20657It is also possible to use @code{GDB} with these traceback addresses to debug 20658the program. For example, we can break at a given code location, as reported 20659in the stack traceback: 20660 20661@smallexample 20662$ gdb -nw stb 20663@ifclear vms 20664@noindent 20665Furthermore, this feature is not implemented inside Windows DLL. Only 20666the non-symbolic traceback is reported in this case. 20667@end ifclear 20668 20669(gdb) break *0x401373 20670Breakpoint 1 at 0x401373: file stb.adb, line 5. 20671@end smallexample 20672 20673@noindent 20674It is important to note that the stack traceback addresses 20675do not change when debug information is included. This is particularly useful 20676because it makes it possible to release software without debug information (to 20677minimize object size), get a field report that includes a stack traceback 20678whenever an internal bug occurs, and then be able to retrieve the sequence 20679of calls with the same program compiled with debug information. 20680 20681@node Tracebacks From Exception Occurrences (non-symbolic) 20682@subsubsection Tracebacks From Exception Occurrences 20683 20684@noindent 20685Non-symbolic tracebacks are obtained by using the @option{-E} binder argument. 20686The stack traceback is attached to the exception information string, and can 20687be retrieved in an exception handler within the Ada program, by means of the 20688Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example: 20689 20690@smallexample @c ada 20691with Ada.Text_IO; 20692with Ada.Exceptions; 20693 20694procedure STB is 20695 20696 use Ada; 20697 use Ada.Exceptions; 20698 20699 procedure P1 is 20700 K : Positive := 1; 20701 begin 20702 K := K - 1; 20703 exception 20704 when E : others => 20705 Text_IO.Put_Line (Exception_Information (E)); 20706 end P1; 20707 20708 procedure P2 is 20709 begin 20710 P1; 20711 end P2; 20712 20713begin 20714 P2; 20715end STB; 20716@end smallexample 20717 20718@noindent 20719This program will output: 20720 20721@smallexample 20722$ stb 20723 20724Exception name: CONSTRAINT_ERROR 20725Message: stb.adb:12 20726Call stack traceback locations: 207270x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4 20728@end smallexample 20729 20730@node Tracebacks From Anywhere in a Program (non-symbolic) 20731@subsubsection Tracebacks From Anywhere in a Program 20732 20733@noindent 20734It is also possible to retrieve a stack traceback from anywhere in a 20735program. For this you need to 20736use the @code{GNAT.Traceback} API. This package includes a procedure called 20737@code{Call_Chain} that computes a complete stack traceback, as well as useful 20738display procedures described below. It is not necessary to use the 20739@option{-E gnatbind} option in this case, because the stack traceback mechanism 20740is invoked explicitly. 20741 20742@noindent 20743In the following example we compute a traceback at a specific location in 20744the program, and we display it using @code{GNAT.Debug_Utilities.Image} to 20745convert addresses to strings: 20746 20747@smallexample @c ada 20748with Ada.Text_IO; 20749with GNAT.Traceback; 20750with GNAT.Debug_Utilities; 20751 20752procedure STB is 20753 20754 use Ada; 20755 use GNAT; 20756 use GNAT.Traceback; 20757 20758 procedure P1 is 20759 TB : Tracebacks_Array (1 .. 10); 20760 -- We are asking for a maximum of 10 stack frames. 20761 Len : Natural; 20762 -- Len will receive the actual number of stack frames returned. 20763 begin 20764 Call_Chain (TB, Len); 20765 20766 Text_IO.Put ("In STB.P1 : "); 20767 20768 for K in 1 .. Len loop 20769 Text_IO.Put (Debug_Utilities.Image (TB (K))); 20770 Text_IO.Put (' '); 20771 end loop; 20772 20773 Text_IO.New_Line; 20774 end P1; 20775 20776 procedure P2 is 20777 begin 20778 P1; 20779 end P2; 20780 20781begin 20782 P2; 20783end STB; 20784@end smallexample 20785 20786@smallexample 20787$ gnatmake -g stb 20788$ stb 20789 20790In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C# 2079116#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4# 20792@end smallexample 20793 20794@noindent 20795You can then get further information by invoking the @code{addr2line} 20796tool as described earlier (note that the hexadecimal addresses 20797need to be specified in C format, with a leading ``0x''). 20798 20799@node Symbolic Traceback 20800@subsection Symbolic Traceback 20801@cindex traceback, symbolic 20802 20803@noindent 20804A symbolic traceback is a stack traceback in which procedure names are 20805associated with each code location. 20806 20807@noindent 20808Note that this feature is not supported on all platforms. See 20809@file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete 20810list of currently supported platforms. 20811 20812@noindent 20813Note that the symbolic traceback requires that the program be compiled 20814with debug information. If it is not compiled with debug information 20815only the non-symbolic information will be valid. 20816 20817@menu 20818* Tracebacks From Exception Occurrences (symbolic):: 20819* Tracebacks From Anywhere in a Program (symbolic):: 20820@end menu 20821 20822@node Tracebacks From Exception Occurrences (symbolic) 20823@subsubsection Tracebacks From Exception Occurrences 20824 20825@smallexample @c ada 20826with Ada.Text_IO; 20827with GNAT.Traceback.Symbolic; 20828 20829procedure STB is 20830 20831 procedure P1 is 20832 begin 20833 raise Constraint_Error; 20834 end P1; 20835 20836 procedure P2 is 20837 begin 20838 P1; 20839 end P2; 20840 20841 procedure P3 is 20842 begin 20843 P2; 20844 end P3; 20845 20846begin 20847 P3; 20848exception 20849 when E : others => 20850 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E)); 20851end STB; 20852@end smallexample 20853 20854@smallexample 20855$ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl 20856$ stb 20857 208580040149F in stb.p1 at stb.adb:8 20859004014B7 in stb.p2 at stb.adb:13 20860004014CF in stb.p3 at stb.adb:18 20861004015DD in ada.stb at stb.adb:22 2086200401461 in main at b~stb.adb:168 20863004011C4 in __mingw_CRTStartup at crt1.c:200 20864004011F1 in mainCRTStartup at crt1.c:222 2086577E892A4 in ?? at ??:0 20866@end smallexample 20867 20868@noindent 20869In the above example the ``.\'' syntax in the @command{gnatmake} command 20870is currently required by @command{addr2line} for files that are in 20871the current working directory. 20872Moreover, the exact sequence of linker options may vary from platform 20873to platform. 20874The above @option{-largs} section is for Windows platforms. By contrast, 20875under Unix there is no need for the @option{-largs} section. 20876Differences across platforms are due to details of linker implementation. 20877 20878@node Tracebacks From Anywhere in a Program (symbolic) 20879@subsubsection Tracebacks From Anywhere in a Program 20880 20881@noindent 20882It is possible to get a symbolic stack traceback 20883from anywhere in a program, just as for non-symbolic tracebacks. 20884The first step is to obtain a non-symbolic 20885traceback, and then call @code{Symbolic_Traceback} to compute the symbolic 20886information. Here is an example: 20887 20888@smallexample @c ada 20889with Ada.Text_IO; 20890with GNAT.Traceback; 20891with GNAT.Traceback.Symbolic; 20892 20893procedure STB is 20894 20895 use Ada; 20896 use GNAT.Traceback; 20897 use GNAT.Traceback.Symbolic; 20898 20899 procedure P1 is 20900 TB : Tracebacks_Array (1 .. 10); 20901 -- We are asking for a maximum of 10 stack frames. 20902 Len : Natural; 20903 -- Len will receive the actual number of stack frames returned. 20904 begin 20905 Call_Chain (TB, Len); 20906 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len))); 20907 end P1; 20908 20909 procedure P2 is 20910 begin 20911 P1; 20912 end P2; 20913 20914begin 20915 P2; 20916end STB; 20917@end smallexample 20918 20919@c ****************************** 20920@ifset vms 20921@node Compatibility with HP Ada 20922@chapter Compatibility with HP Ada 20923@cindex Compatibility 20924 20925@noindent 20926@cindex DEC Ada 20927@cindex HP Ada 20928@cindex Compatibility between GNAT and HP Ada 20929This chapter compares HP Ada (formerly known as ``DEC Ada'') 20930for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64. 20931GNAT is highly compatible 20932with HP Ada, and it should generally be straightforward to port code 20933from the HP Ada environment to GNAT. However, there are a few language 20934and implementation differences of which the user must be aware. These 20935differences are discussed in this chapter. In 20936addition, the operating environment and command structure for the 20937compiler are different, and these differences are also discussed. 20938 20939For further details on these and other compatibility issues, 20940see Appendix E of the HP publication 20941@cite{HP Ada, Technical Overview and Comparison on HP Platforms}. 20942 20943Except where otherwise indicated, the description of GNAT for OpenVMS 20944applies to both the Alpha and I64 platforms. 20945 20946For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on 20947I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}. 20948 20949The discussion in this chapter addresses specifically the implementation 20950of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation 20951of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, 20952GNAT always follows the Alpha implementation. 20953 20954For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and 20955attributes are recognized, although only a subset of them can sensibly 20956be implemented. The description of pragmas in 20957@xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual}, 20958indicates whether or not they are applicable to non-VMS systems. 20959 20960@menu 20961* Ada Language Compatibility:: 20962* Differences in the Definition of Package System:: 20963* Language-Related Features:: 20964* The Package STANDARD:: 20965* The Package SYSTEM:: 20966* Tasking and Task-Related Features:: 20967* Pragmas and Pragma-Related Features:: 20968* Library of Predefined Units:: 20969* Bindings:: 20970* Main Program Definition:: 20971* Implementation-Defined Attributes:: 20972* Compiler and Run-Time Interfacing:: 20973* Program Compilation and Library Management:: 20974* Input-Output:: 20975* Implementation Limits:: 20976* Tools and Utilities:: 20977@end menu 20978 20979@node Ada Language Compatibility 20980@section Ada Language Compatibility 20981 20982@noindent 20983GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only 20984for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible 20985with Ada 83, and therefore Ada 83 programs will compile 20986and run under GNAT with 20987no changes or only minor changes. The @cite{Annotated Ada Reference Manual} 20988provides details on specific incompatibilities. 20989 20990GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command, 20991as well as the pragma @code{ADA_83}, to force the compiler to 20992operate in Ada 83 mode. This mode does not guarantee complete 20993conformance to Ada 83, but in practice is sufficient to 20994eliminate most sources of incompatibilities. 20995In particular, it eliminates the recognition of the 20996additional Ada 95 and Ada 2005 keywords, so that their use as identifiers 20997in Ada 83 programs is legal, and handles the cases of packages 20998with optional bodies, and generics that instantiate unconstrained 20999types without the use of @code{(<>)}. 21000 21001@node Differences in the Definition of Package System 21002@section Differences in the Definition of Package @code{System} 21003 21004@noindent 21005An Ada compiler is allowed to add 21006implementation-dependent declarations to package @code{System}. 21007In normal mode, 21008GNAT does not take advantage of this permission, and the version of 21009@code{System} provided by GNAT exactly matches that defined in the Ada 21010Reference Manual. 21011 21012However, HP Ada adds an extensive set of declarations to package 21013@code{System}, 21014as fully documented in the HP Ada manuals. To minimize changes required 21015for programs that make use of these extensions, GNAT provides the pragma 21016@code{Extend_System} for extending the definition of package System. By using: 21017@cindex pragma @code{Extend_System} 21018@cindex @code{Extend_System} pragma 21019 21020@smallexample @c ada 21021@group 21022@cartouche 21023pragma Extend_System (Aux_DEC); 21024@end cartouche 21025@end group 21026@end smallexample 21027 21028@noindent 21029the set of definitions in @code{System} is extended to include those in 21030package @code{System.Aux_DEC}. 21031@cindex @code{System.Aux_DEC} package 21032@cindex @code{Aux_DEC} package (child of @code{System}) 21033These definitions are incorporated directly into package @code{System}, 21034as though they had been declared there. For a 21035list of the declarations added, see the spec of this package, 21036which can be found in the file @file{s-auxdec.ads} in the GNAT library. 21037@cindex @file{s-auxdec.ads} file 21038The pragma @code{Extend_System} is a configuration pragma, which means that 21039it can be placed in the file @file{gnat.adc}, so that it will automatically 21040apply to all subsequent compilations. See @ref{Configuration Pragmas}, 21041for further details. 21042 21043An alternative approach that avoids the use of the non-standard 21044@code{Extend_System} pragma is to add a context clause to the unit that 21045references these facilities: 21046 21047@smallexample @c ada 21048@cartouche 21049with System.Aux_DEC; 21050use System.Aux_DEC; 21051@end cartouche 21052@end smallexample 21053 21054@noindent 21055The effect is not quite semantically identical to incorporating 21056the declarations directly into package @code{System}, 21057but most programs will not notice a difference 21058unless they use prefix notation (e.g.@: @code{System.Integer_8}) 21059to reference the entities directly in package @code{System}. 21060For units containing such references, 21061the prefixes must either be removed, or the pragma @code{Extend_System} 21062must be used. 21063 21064@node Language-Related Features 21065@section Language-Related Features 21066 21067@noindent 21068The following sections highlight differences in types, 21069representations of types, operations, alignment, and 21070related topics. 21071 21072@menu 21073* Integer Types and Representations:: 21074* Floating-Point Types and Representations:: 21075* Pragmas Float_Representation and Long_Float:: 21076* Fixed-Point Types and Representations:: 21077* Record and Array Component Alignment:: 21078* Address Clauses:: 21079* Other Representation Clauses:: 21080@end menu 21081 21082@node Integer Types and Representations 21083@subsection Integer Types and Representations 21084 21085@noindent 21086The set of predefined integer types is identical in HP Ada and GNAT. 21087Furthermore the representation of these integer types is also identical, 21088including the capability of size clauses forcing biased representation. 21089 21090In addition, 21091HP Ada for OpenVMS Alpha systems has defined the 21092following additional integer types in package @code{System}: 21093 21094@itemize @bullet 21095 21096@item 21097@code{INTEGER_8} 21098 21099@item 21100@code{INTEGER_16} 21101 21102@item 21103@code{INTEGER_32} 21104 21105@item 21106@code{INTEGER_64} 21107 21108@item 21109@code{LARGEST_INTEGER} 21110@end itemize 21111 21112@noindent 21113In GNAT, the first four of these types may be obtained from the 21114standard Ada package @code{Interfaces}. 21115Alternatively, by use of the pragma @code{Extend_System}, identical 21116declarations can be referenced directly in package @code{System}. 21117On both GNAT and HP Ada, the maximum integer size is 64 bits. 21118 21119@node Floating-Point Types and Representations 21120@subsection Floating-Point Types and Representations 21121@cindex Floating-Point types 21122 21123@noindent 21124The set of predefined floating-point types is identical in HP Ada and GNAT. 21125Furthermore the representation of these floating-point 21126types is also identical. One important difference is that the default 21127representation for HP Ada is @code{VAX_Float}, but the default representation 21128for GNAT is IEEE. 21129 21130Specific types may be declared to be @code{VAX_Float} or IEEE, using the 21131pragma @code{Float_Representation} as described in the HP Ada 21132documentation. 21133For example, the declarations: 21134 21135@smallexample @c ada 21136@cartouche 21137type F_Float is digits 6; 21138pragma Float_Representation (VAX_Float, F_Float); 21139@end cartouche 21140@end smallexample 21141 21142@noindent 21143declares a type @code{F_Float} that will be represented in @code{VAX_Float} 21144format. 21145This set of declarations actually appears in @code{System.Aux_DEC}, 21146which contains 21147the full set of additional floating-point declarations provided in 21148the HP Ada version of package @code{System}. 21149This and similar declarations may be accessed in a user program 21150by using pragma @code{Extend_System}. The use of this 21151pragma, and the related pragma @code{Long_Float} is described in further 21152detail in the following section. 21153 21154@node Pragmas Float_Representation and Long_Float 21155@subsection Pragmas @code{Float_Representation} and @code{Long_Float} 21156 21157@noindent 21158HP Ada provides the pragma @code{Float_Representation}, which 21159acts as a program library switch to allow control over 21160the internal representation chosen for the predefined 21161floating-point types declared in the package @code{Standard}. 21162The format of this pragma is as follows: 21163 21164@smallexample @c ada 21165@cartouche 21166pragma Float_Representation(VAX_Float | IEEE_Float); 21167@end cartouche 21168@end smallexample 21169 21170@noindent 21171This pragma controls the representation of floating-point 21172types as follows: 21173 21174@itemize @bullet 21175@item 21176@code{VAX_Float} specifies that floating-point 21177types are represented by default with the VAX system hardware types 21178@code{F-floating}, @code{D-floating}, @code{G-floating}. 21179Note that the @code{H-floating} 21180type was available only on VAX systems, and is not available 21181in either HP Ada or GNAT. 21182 21183@item 21184@code{IEEE_Float} specifies that floating-point 21185types are represented by default with the IEEE single and 21186double floating-point types. 21187@end itemize 21188 21189@noindent 21190GNAT provides an identical implementation of the pragma 21191@code{Float_Representation}, except that it functions as a 21192configuration pragma. Note that the 21193notion of configuration pragma corresponds closely to the 21194HP Ada notion of a program library switch. 21195 21196When no pragma is used in GNAT, the default is @code{IEEE_Float}, 21197which is different 21198from HP Ada 83, where the default is @code{VAX_Float}. In addition, the 21199predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not 21200advisable to change the format of numbers passed to standard library 21201routines, and if necessary explicit type conversions may be needed. 21202 21203The use of @code{IEEE_Float} is recommended in GNAT since it is more 21204efficient, and (given that it conforms to an international standard) 21205potentially more portable. 21206The situation in which @code{VAX_Float} may be useful is in interfacing 21207to existing code and data that expect the use of @code{VAX_Float}. 21208In such a situation use the predefined @code{VAX_Float} 21209types in package @code{System}, as extended by 21210@code{Extend_System}. For example, use @code{System.F_Float} 21211to specify the 32-bit @code{F-Float} format. 21212 21213@noindent 21214On OpenVMS systems, HP Ada provides the pragma @code{Long_Float} 21215to allow control over the internal representation chosen 21216for the predefined type @code{Long_Float} and for floating-point 21217type declarations with digits specified in the range 7 .. 15. 21218The format of this pragma is as follows: 21219 21220@smallexample @c ada 21221@cartouche 21222pragma Long_Float (D_FLOAT | G_FLOAT); 21223@end cartouche 21224@end smallexample 21225 21226@node Fixed-Point Types and Representations 21227@subsection Fixed-Point Types and Representations 21228 21229@noindent 21230On HP Ada for OpenVMS Alpha systems, rounding is 21231away from zero for both positive and negative numbers. 21232Therefore, @code{+0.5} rounds to @code{1}, 21233and @code{-0.5} rounds to @code{-1}. 21234 21235On GNAT the results of operations 21236on fixed-point types are in accordance with the Ada 21237rules. In particular, results of operations on decimal 21238fixed-point types are truncated. 21239 21240@node Record and Array Component Alignment 21241@subsection Record and Array Component Alignment 21242 21243@noindent 21244On HP Ada for OpenVMS Alpha, all non-composite components 21245are aligned on natural boundaries. For example, 1-byte 21246components are aligned on byte boundaries, 2-byte 21247components on 2-byte boundaries, 4-byte components on 4-byte 21248byte boundaries, and so on. The OpenVMS Alpha hardware 21249runs more efficiently with naturally aligned data. 21250 21251On GNAT, alignment rules are compatible 21252with HP Ada for OpenVMS Alpha. 21253 21254@node Address Clauses 21255@subsection Address Clauses 21256 21257@noindent 21258In HP Ada and GNAT, address clauses are supported for 21259objects and imported subprograms. 21260The predefined type @code{System.Address} is a private type 21261in both compilers on Alpha OpenVMS, with the same representation 21262(it is simply a machine pointer). Addition, subtraction, and comparison 21263operations are available in the standard Ada package 21264@code{System.Storage_Elements}, or in package @code{System} 21265if it is extended to include @code{System.Aux_DEC} using a 21266pragma @code{Extend_System} as previously described. 21267 21268Note that code that @code{with}'s both this extended package @code{System} 21269and the package @code{System.Storage_Elements} should not @code{use} 21270both packages, or ambiguities will result. In general it is better 21271not to mix these two sets of facilities. The Ada package was 21272designed specifically to provide the kind of features that HP Ada 21273adds directly to package @code{System}. 21274 21275The type @code{System.Address} is a 64-bit integer type in GNAT for 21276I64 OpenVMS. For more information, 21277see @ref{Transitioning to 64-Bit GNAT for OpenVMS}. 21278 21279GNAT is compatible with HP Ada in its handling of address 21280clauses, except for some limitations in 21281the form of address clauses for composite objects with 21282initialization. Such address clauses are easily replaced 21283by the use of an explicitly-defined constant as described 21284in the Ada Reference Manual (13.1(22)). For example, the sequence 21285of declarations: 21286 21287@smallexample @c ada 21288@cartouche 21289X, Y : Integer := Init_Func; 21290Q : String (X .. Y) := "abc"; 21291@dots{} 21292for Q'Address use Compute_Address; 21293@end cartouche 21294@end smallexample 21295 21296@noindent 21297will be rejected by GNAT, since the address cannot be computed at the time 21298that @code{Q} is declared. To achieve the intended effect, write instead: 21299 21300@smallexample @c ada 21301@group 21302@cartouche 21303X, Y : Integer := Init_Func; 21304Q_Address : constant Address := Compute_Address; 21305Q : String (X .. Y) := "abc"; 21306@dots{} 21307for Q'Address use Q_Address; 21308@end cartouche 21309@end group 21310@end smallexample 21311 21312@noindent 21313which will be accepted by GNAT (and other Ada compilers), and is also 21314compatible with Ada 83. A fuller description of the restrictions 21315on address specifications is found in @ref{Top, GNAT Reference Manual, 21316About This Guide, gnat_rm, GNAT Reference Manual}. 21317 21318@node Other Representation Clauses 21319@subsection Other Representation Clauses 21320 21321@noindent 21322GNAT implements in a compatible manner all the representation 21323clauses supported by HP Ada. In addition, GNAT 21324implements the representation clause forms that were introduced in Ada 95, 21325including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects. 21326 21327@node The Package STANDARD 21328@section The Package @code{STANDARD} 21329 21330@noindent 21331The package @code{STANDARD}, as implemented by HP Ada, is fully 21332described in the @cite{Ada Reference Manual} and in the 21333@cite{HP Ada Language Reference Manual}. As implemented by GNAT, the 21334package @code{STANDARD} is described in the @cite{Ada Reference Manual}. 21335 21336In addition, HP Ada supports the Latin-1 character set in 21337the type @code{CHARACTER}. GNAT supports the Latin-1 character set 21338in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in 21339the type @code{WIDE_CHARACTER}. 21340 21341The floating-point types supported by GNAT are those 21342supported by HP Ada, but the defaults are different, and are controlled by 21343pragmas. See @ref{Floating-Point Types and Representations}, for details. 21344 21345@node The Package SYSTEM 21346@section The Package @code{SYSTEM} 21347 21348@noindent 21349HP Ada provides a specific version of the package 21350@code{SYSTEM} for each platform on which the language is implemented. 21351For the complete spec of the package @code{SYSTEM}, see 21352Appendix F of the @cite{HP Ada Language Reference Manual}. 21353 21354On HP Ada, the package @code{SYSTEM} includes the following conversion 21355functions: 21356@itemize @bullet 21357@item @code{TO_ADDRESS(INTEGER)} 21358 21359@item @code{TO_ADDRESS(UNSIGNED_LONGWORD)} 21360 21361@item @code{TO_ADDRESS(}@i{universal_integer}@code{)} 21362 21363@item @code{TO_INTEGER(ADDRESS)} 21364 21365@item @code{TO_UNSIGNED_LONGWORD(ADDRESS)} 21366 21367@item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the 21368functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE} 21369@end itemize 21370 21371@noindent 21372By default, GNAT supplies a version of @code{SYSTEM} that matches 21373the definition given in the @cite{Ada Reference Manual}. 21374This 21375is a subset of the HP system definitions, which is as 21376close as possible to the original definitions. The only difference 21377is that the definition of @code{SYSTEM_NAME} is different: 21378 21379@smallexample @c ada 21380@cartouche 21381type Name is (SYSTEM_NAME_GNAT); 21382System_Name : constant Name := SYSTEM_NAME_GNAT; 21383@end cartouche 21384@end smallexample 21385 21386@noindent 21387Also, GNAT adds the Ada declarations for 21388@code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}. 21389 21390However, the use of the following pragma causes GNAT 21391to extend the definition of package @code{SYSTEM} so that it 21392encompasses the full set of HP-specific extensions, 21393including the functions listed above: 21394 21395@smallexample @c ada 21396@cartouche 21397pragma Extend_System (Aux_DEC); 21398@end cartouche 21399@end smallexample 21400 21401@noindent 21402The pragma @code{Extend_System} is a configuration pragma that 21403is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma 21404Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details. 21405 21406HP Ada does not allow the recompilation of the package 21407@code{SYSTEM}. Instead HP Ada provides several pragmas 21408(@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE}) 21409to modify values in the package @code{SYSTEM}. 21410On OpenVMS Alpha systems, the pragma 21411@code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as 21412its single argument. 21413 21414GNAT does permit the recompilation of package @code{SYSTEM} using 21415the special switch @option{-gnatg}, and this switch can be used if 21416it is necessary to modify the definitions in @code{SYSTEM}. GNAT does 21417not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT} 21418or @code{MEMORY_SIZE} by any other means. 21419 21420On GNAT systems, the pragma @code{SYSTEM_NAME} takes the 21421enumeration literal @code{SYSTEM_NAME_GNAT}. 21422 21423The definitions provided by the use of 21424 21425@smallexample @c ada 21426pragma Extend_System (AUX_Dec); 21427@end smallexample 21428 21429@noindent 21430are virtually identical to those provided by the HP Ada 83 package 21431@code{SYSTEM}. One important difference is that the name of the 21432@code{TO_ADDRESS} 21433function for type @code{UNSIGNED_LONGWORD} is changed to 21434@code{TO_ADDRESS_LONG}. 21435@xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a 21436discussion of why this change was necessary. 21437 21438@noindent 21439The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument 21440is in fact 21441an extension to Ada 83 not strictly compatible with the reference manual. 21442GNAT, in order to be exactly compatible with the standard, 21443does not provide this capability. In HP Ada 83, the 21444point of this definition is to deal with a call like: 21445 21446@smallexample @c ada 21447TO_ADDRESS (16#12777#); 21448@end smallexample 21449 21450@noindent 21451Normally, according to Ada 83 semantics, one would expect this to be 21452ambiguous, since it matches both the @code{INTEGER} and 21453@code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}. 21454However, in HP Ada 83, there is no ambiguity, since the 21455definition using @i{universal_integer} takes precedence. 21456 21457In GNAT, since the version with @i{universal_integer} cannot be supplied, 21458it is 21459not possible to be 100% compatible. Since there are many programs using 21460numeric constants for the argument to @code{TO_ADDRESS}, the decision in 21461GNAT was 21462to change the name of the function in the @code{UNSIGNED_LONGWORD} case, 21463so the declarations provided in the GNAT version of @code{AUX_Dec} are: 21464 21465@smallexample @c ada 21466function To_Address (X : Integer) return Address; 21467pragma Pure_Function (To_Address); 21468 21469function To_Address_Long (X : Unsigned_Longword) return Address; 21470pragma Pure_Function (To_Address_Long); 21471@end smallexample 21472 21473@noindent 21474This means that programs using @code{TO_ADDRESS} for 21475@code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}. 21476 21477@node Tasking and Task-Related Features 21478@section Tasking and Task-Related Features 21479 21480@noindent 21481This section compares the treatment of tasking in GNAT 21482and in HP Ada for OpenVMS Alpha. 21483The GNAT description applies to both Alpha and I64 OpenVMS. 21484For detailed information on tasking in 21485HP Ada, see the @cite{HP Ada Language Reference Manual} and the 21486relevant run-time reference manual. 21487 21488@menu 21489* Implementation of Tasks in HP Ada for OpenVMS Alpha Systems:: 21490* Assigning Task IDs:: 21491* Task IDs and Delays:: 21492* Task-Related Pragmas:: 21493* Scheduling and Task Priority:: 21494* The Task Stack:: 21495* External Interrupts:: 21496@end menu 21497 21498@node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems 21499@subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems 21500 21501@noindent 21502On OpenVMS Alpha systems, each Ada task (except a passive 21503task) is implemented as a single stream of execution 21504that is created and managed by the kernel. On these 21505systems, HP Ada tasking support is based on DECthreads, 21506an implementation of the POSIX standard for threads. 21507 21508Also, on OpenVMS Alpha systems, HP Ada tasks and foreign 21509code that calls DECthreads routines can be used together. 21510The interaction between Ada tasks and DECthreads routines 21511can have some benefits. For example when on OpenVMS Alpha, 21512HP Ada can call C code that is already threaded. 21513 21514GNAT uses the facilities of DECthreads, 21515and Ada tasks are mapped to threads. 21516 21517@node Assigning Task IDs 21518@subsection Assigning Task IDs 21519 21520@noindent 21521The HP Ada Run-Time Library always assigns @code{%TASK 1} to 21522the environment task that executes the main program. On 21523OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks 21524that have been created but are not yet activated. 21525 21526On OpenVMS Alpha systems, task IDs are assigned at 21527activation. On GNAT systems, task IDs are also assigned at 21528task creation but do not have the same form or values as 21529task ID values in HP Ada. There is no null task, and the 21530environment task does not have a specific task ID value. 21531 21532@node Task IDs and Delays 21533@subsection Task IDs and Delays 21534 21535@noindent 21536On OpenVMS Alpha systems, tasking delays are implemented 21537using Timer System Services. The Task ID is used for the 21538identification of the timer request (the @code{REQIDT} parameter). 21539If Timers are used in the application take care not to use 21540@code{0} for the identification, because cancelling such a timer 21541will cancel all timers and may lead to unpredictable results. 21542 21543@node Task-Related Pragmas 21544@subsection Task-Related Pragmas 21545 21546@noindent 21547Ada supplies the pragma @code{TASK_STORAGE}, which allows 21548specification of the size of the guard area for a task 21549stack. (The guard area forms an area of memory that has no 21550read or write access and thus helps in the detection of 21551stack overflow.) On OpenVMS Alpha systems, if the pragma 21552@code{TASK_STORAGE} specifies a value of zero, a minimal guard 21553area is created. In the absence of a pragma @code{TASK_STORAGE}, 21554a default guard area is created. 21555 21556GNAT supplies the following task-related pragmas: 21557 21558@itemize @bullet 21559@item @code{TASK_INFO} 21560 21561This pragma appears within a task definition and 21562applies to the task in which it appears. The argument 21563must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}. 21564 21565@item @code{TASK_STORAGE} 21566 21567GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada. 21568Both HP Ada and GNAT supply the pragmas @code{PASSIVE}, 21569@code{SUPPRESS}, and @code{VOLATILE}. 21570@end itemize 21571@node Scheduling and Task Priority 21572@subsection Scheduling and Task Priority 21573 21574@noindent 21575HP Ada implements the Ada language requirement that 21576when two tasks are eligible for execution and they have 21577different priorities, the lower priority task does not 21578execute while the higher priority task is waiting. The HP 21579Ada Run-Time Library keeps a task running until either the 21580task is suspended or a higher priority task becomes ready. 21581 21582On OpenVMS Alpha systems, the default strategy is round- 21583robin with preemption. Tasks of equal priority take turns 21584at the processor. A task is run for a certain period of 21585time and then placed at the tail of the ready queue for 21586its priority level. 21587 21588HP Ada provides the implementation-defined pragma @code{TIME_SLICE}, 21589which can be used to enable or disable round-robin 21590scheduling of tasks with the same priority. 21591See the relevant HP Ada run-time reference manual for 21592information on using the pragmas to control HP Ada task 21593scheduling. 21594 21595GNAT follows the scheduling rules of Annex D (Real-Time 21596Annex) of the @cite{Ada Reference Manual}. In general, this 21597scheduling strategy is fully compatible with HP Ada 21598although it provides some additional constraints (as 21599fully documented in Annex D). 21600GNAT implements time slicing control in a manner compatible with 21601HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics 21602are identical to the HP Ada 83 pragma of the same name. 21603Note that it is not possible to mix GNAT tasking and 21604HP Ada 83 tasking in the same program, since the two run-time 21605libraries are not compatible. 21606 21607@node The Task Stack 21608@subsection The Task Stack 21609 21610@noindent 21611In HP Ada, a task stack is allocated each time a 21612non-passive task is activated. As soon as the task is 21613terminated, the storage for the task stack is deallocated. 21614If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE}, 21615a default stack size is used. Also, regardless of the size 21616specified, some additional space is allocated for task 21617management purposes. On OpenVMS Alpha systems, at least 21618one page is allocated. 21619 21620GNAT handles task stacks in a similar manner. In accordance with 21621the Ada rules, it provides the pragma @code{STORAGE_SIZE} as 21622an alternative method for controlling the task stack size. 21623The specification of the attribute @code{T'STORAGE_SIZE} is also 21624supported in a manner compatible with HP Ada. 21625 21626@node External Interrupts 21627@subsection External Interrupts 21628 21629@noindent 21630On HP Ada, external interrupts can be associated with task entries. 21631GNAT is compatible with HP Ada in its handling of external interrupts. 21632 21633@node Pragmas and Pragma-Related Features 21634@section Pragmas and Pragma-Related Features 21635 21636@noindent 21637Both HP Ada and GNAT supply all language-defined pragmas 21638as specified by the Ada 83 standard. GNAT also supplies all 21639language-defined pragmas introduced by Ada 95 and Ada 2005. 21640In addition, GNAT implements the implementation-defined pragmas 21641from HP Ada 83. 21642 21643@itemize @bullet 21644@item @code{AST_ENTRY} 21645 21646@item @code{COMMON_OBJECT} 21647 21648@item @code{COMPONENT_ALIGNMENT} 21649 21650@item @code{EXPORT_EXCEPTION} 21651 21652@item @code{EXPORT_FUNCTION} 21653 21654@item @code{EXPORT_OBJECT} 21655 21656@item @code{EXPORT_PROCEDURE} 21657 21658@item @code{EXPORT_VALUED_PROCEDURE} 21659 21660@item @code{FLOAT_REPRESENTATION} 21661 21662@item @code{IDENT} 21663 21664@item @code{IMPORT_EXCEPTION} 21665 21666@item @code{IMPORT_FUNCTION} 21667 21668@item @code{IMPORT_OBJECT} 21669 21670@item @code{IMPORT_PROCEDURE} 21671 21672@item @code{IMPORT_VALUED_PROCEDURE} 21673 21674@item @code{INLINE_GENERIC} 21675 21676@item @code{INTERFACE_NAME} 21677 21678@item @code{LONG_FLOAT} 21679 21680@item @code{MAIN_STORAGE} 21681 21682@item @code{PASSIVE} 21683 21684@item @code{PSECT_OBJECT} 21685 21686@item @code{SHARE_GENERIC} 21687 21688@item @code{SUPPRESS_ALL} 21689 21690@item @code{TASK_STORAGE} 21691 21692@item @code{TIME_SLICE} 21693 21694@item @code{TITLE} 21695@end itemize 21696 21697@noindent 21698These pragmas are all fully implemented, with the exception of @code{TITLE}, 21699@code{PASSIVE}, and @code{SHARE_GENERIC}, which are 21700recognized, but which have no 21701effect in GNAT. The effect of @code{PASSIVE} may be obtained by the 21702use of Ada protected objects. In GNAT, all generics are inlined. 21703 21704Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require 21705a separate subprogram specification which must appear before the 21706subprogram body. 21707 21708GNAT also supplies a number of implementation-defined pragmas including the 21709following: 21710 21711@itemize @bullet 21712@item @code{ABORT_DEFER} 21713 21714@item @code{ADA_83} 21715 21716@item @code{ADA_95} 21717 21718@item @code{ADA_05} 21719 21720@item @code{Ada_2005} 21721 21722@item @code{Ada_12} 21723 21724@item @code{Ada_2012} 21725 21726@item @code{ANNOTATE} 21727 21728@item @code{ASSERT} 21729 21730@item @code{C_PASS_BY_COPY} 21731 21732@item @code{CPP_CLASS} 21733 21734@item @code{CPP_CONSTRUCTOR} 21735 21736@item @code{CPP_DESTRUCTOR} 21737 21738@item @code{DEBUG} 21739 21740@item @code{EXTEND_SYSTEM} 21741 21742@item @code{LINKER_ALIAS} 21743 21744@item @code{LINKER_SECTION} 21745 21746@item @code{MACHINE_ATTRIBUTE} 21747 21748@item @code{NO_RETURN} 21749 21750@item @code{PURE_FUNCTION} 21751 21752@item @code{SOURCE_FILE_NAME} 21753 21754@item @code{SOURCE_REFERENCE} 21755 21756@item @code{TASK_INFO} 21757 21758@item @code{UNCHECKED_UNION} 21759 21760@item @code{UNIMPLEMENTED_UNIT} 21761 21762@item @code{UNIVERSAL_DATA} 21763 21764@item @code{UNSUPPRESS} 21765 21766@item @code{WARNINGS} 21767 21768@item @code{WEAK_EXTERNAL} 21769@end itemize 21770 21771@noindent 21772For full details on these and other GNAT implementation-defined pragmas, 21773see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference 21774Manual}. 21775 21776@menu 21777* Restrictions on the Pragma INLINE:: 21778* Restrictions on the Pragma INTERFACE:: 21779* Restrictions on the Pragma SYSTEM_NAME:: 21780@end menu 21781 21782@node Restrictions on the Pragma INLINE 21783@subsection Restrictions on Pragma @code{INLINE} 21784 21785@noindent 21786HP Ada enforces the following restrictions on the pragma @code{INLINE}: 21787@itemize @bullet 21788@item Parameters cannot have a task type. 21789 21790@item Function results cannot be task types, unconstrained 21791array types, or unconstrained types with discriminants. 21792 21793@item Bodies cannot declare the following: 21794@itemize @bullet 21795@item Subprogram body or stub (imported subprogram is allowed) 21796 21797@item Tasks 21798 21799@item Generic declarations 21800 21801@item Instantiations 21802 21803@item Exceptions 21804 21805@item Access types (types derived from access types allowed) 21806 21807@item Array or record types 21808 21809@item Dependent tasks 21810 21811@item Direct recursive calls of subprogram or containing 21812subprogram, directly or via a renaming 21813 21814@end itemize 21815@end itemize 21816 21817@noindent 21818In GNAT, the only restriction on pragma @code{INLINE} is that the 21819body must occur before the call if both are in the same 21820unit, and the size must be appropriately small. There are 21821no other specific restrictions which cause subprograms to 21822be incapable of being inlined. 21823 21824@node Restrictions on the Pragma INTERFACE 21825@subsection Restrictions on Pragma @code{INTERFACE} 21826 21827@noindent 21828The following restrictions on pragma @code{INTERFACE} 21829are enforced by both HP Ada and GNAT: 21830@itemize @bullet 21831@item Languages accepted: Ada, Bliss, C, Fortran, Default. 21832Default is the default on OpenVMS Alpha systems. 21833 21834@item Parameter passing: Language specifies default 21835mechanisms but can be overridden with an @code{EXPORT} pragma. 21836 21837@itemize @bullet 21838@item Ada: Use internal Ada rules. 21839 21840@item Bliss, C: Parameters must be mode @code{in}; cannot be 21841record or task type. Result cannot be a string, an 21842array, or a record. 21843 21844@item Fortran: Parameters cannot have a task type. Result cannot 21845be a string, an array, or a record. 21846@end itemize 21847@end itemize 21848 21849@noindent 21850GNAT is entirely upwards compatible with HP Ada, and in addition allows 21851record parameters for all languages. 21852 21853@node Restrictions on the Pragma SYSTEM_NAME 21854@subsection Restrictions on Pragma @code{SYSTEM_NAME} 21855 21856@noindent 21857For HP Ada for OpenVMS Alpha, the enumeration literal 21858for the type @code{NAME} is @code{OPENVMS_AXP}. 21859In GNAT, the enumeration 21860literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}. 21861 21862@node Library of Predefined Units 21863@section Library of Predefined Units 21864 21865@noindent 21866A library of predefined units is provided as part of the 21867HP Ada and GNAT implementations. HP Ada does not provide 21868the package @code{MACHINE_CODE} but instead recommends importing 21869assembler code. 21870 21871The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:}) 21872units are taken from the OpenVMS Alpha version, not the OpenVMS VAX 21873version. 21874The HP Ada Predefined Library units are modified to remove post-Ada 83 21875incompatibilities and to make them interoperable with GNAT 21876(@pxref{Changes to DECLIB}, for details). 21877The units are located in the @file{DECLIB} directory. 21878 21879The GNAT RTL is contained in 21880the @file{ADALIB} directory, and 21881the default search path is set up to find @code{DECLIB} units in preference 21882to @code{ADALIB} units with the same name (@code{TEXT_IO}, 21883@code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example). 21884 21885@menu 21886* Changes to DECLIB:: 21887@end menu 21888 21889@node Changes to DECLIB 21890@subsection Changes to @code{DECLIB} 21891 21892@noindent 21893The changes made to the HP Ada predefined library for GNAT and post-Ada 83 21894compatibility are minor and include the following: 21895 21896@itemize @bullet 21897@item Adjusting the location of pragmas and record representation 21898clauses to obey Ada 95 (and thus Ada 2005) rules 21899 21900@item Adding the proper notation to generic formal parameters 21901that take unconstrained types in instantiation 21902 21903@item Adding pragma @code{ELABORATE_BODY} to package specs 21904that have package bodies not otherwise allowed 21905 21906@item Replacing occurrences of the identifier ``@code{PROTECTED}'' by 21907``@code{PROTECTD}''. 21908Currently these are found only in the @code{STARLET} package spec. 21909 21910@item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS} 21911where the address size is constrained to 32 bits. 21912@end itemize 21913 21914@noindent 21915None of the above changes is visible to users. 21916 21917@node Bindings 21918@section Bindings 21919 21920@noindent 21921On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings: 21922@itemize @bullet 21923 21924@item Command Language Interpreter (CLI interface) 21925 21926@item DECtalk Run-Time Library (DTK interface) 21927 21928@item Librarian utility routines (LBR interface) 21929 21930@item General Purpose Run-Time Library (LIB interface) 21931 21932@item Math Run-Time Library (MTH interface) 21933 21934@item National Character Set Run-Time Library (NCS interface) 21935 21936@item Compiled Code Support Run-Time Library (OTS interface) 21937 21938@item Parallel Processing Run-Time Library (PPL interface) 21939 21940@item Screen Management Run-Time Library (SMG interface) 21941 21942@item Sort Run-Time Library (SOR interface) 21943 21944@item String Run-Time Library (STR interface) 21945 21946@item STARLET System Library 21947@findex Starlet 21948 21949@item X Window System Version 11R4 and 11R5 (X, XLIB interface) 21950 21951@item X Windows Toolkit (XT interface) 21952 21953@item X/Motif Version 1.1.3 and 1.2 (XM interface) 21954@end itemize 21955 21956@noindent 21957GNAT provides implementations of these HP bindings in the @code{DECLIB} 21958directory, on both the Alpha and I64 OpenVMS platforms. 21959 21960The X components of DECLIB compatibility package are located in a separate 21961library, called XDECGNAT, which is not linked with by default; this library 21962must be explicitly linked with any application that makes use of any X facilities, 21963with a command similar to 21964 21965@code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT} 21966 21967The X/Motif bindings used to build @code{DECLIB} are whatever versions are 21968in the 21969HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}. 21970A pragma @code{Linker_Options} has been added to packages @code{Xm}, 21971@code{Xt}, and @code{X_Lib} 21972causing the default X/Motif sharable image libraries to be linked in. This 21973is done via options files named @file{xm.opt}, @file{xt.opt}, and 21974@file{x_lib.opt} (also located in the @file{DECLIB} directory). 21975 21976It may be necessary to edit these options files to update or correct the 21977library names if, for example, the newer X/Motif bindings from 21978@file{ADA$EXAMPLES} 21979had been (previous to installing GNAT) copied and renamed to supersede the 21980default @file{ADA$PREDEFINED} versions. 21981 21982@menu 21983* Shared Libraries and Options Files:: 21984* Interfaces to C:: 21985@end menu 21986 21987@node Shared Libraries and Options Files 21988@subsection Shared Libraries and Options Files 21989 21990@noindent 21991When using the HP Ada 21992predefined X and Motif bindings, the linking with their sharable images is 21993done automatically by @command{GNAT LINK}. 21994When using other X and Motif bindings, you need 21995to add the corresponding sharable images to the command line for 21996@code{GNAT LINK}. When linking with shared libraries, or with 21997@file{.OPT} files, you must 21998also add them to the command line for @command{GNAT LINK}. 21999 22000A shared library to be used with GNAT is built in the same way as other 22001libraries under VMS. The VMS Link command can be used in standard fashion. 22002 22003@node Interfaces to C 22004@subsection Interfaces to C 22005 22006@noindent 22007HP Ada 22008provides the following Ada types and operations: 22009 22010@itemize @bullet 22011@item C types package (@code{C_TYPES}) 22012 22013@item C strings (@code{C_TYPES.NULL_TERMINATED}) 22014 22015@item Other_types (@code{SHORT_INT}) 22016@end itemize 22017 22018@noindent 22019Interfacing to C with GNAT, you can use the above approach 22020described for HP Ada or the facilities of Annex B of 22021the @cite{Ada Reference Manual} (packages @code{INTERFACES.C}, 22022@code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more 22023information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}. 22024 22025The @option{-gnatF} qualifier forces default and explicit 22026@code{External_Name} parameters in pragmas @code{Import} and @code{Export} 22027to be uppercased for compatibility with the default behavior 22028of HP C. The qualifier has no effect on @code{Link_Name} parameters. 22029 22030@node Main Program Definition 22031@section Main Program Definition 22032 22033@noindent 22034The following section discusses differences in the 22035definition of main programs on HP Ada and GNAT. 22036On HP Ada, main programs are defined to meet the 22037following conditions: 22038@itemize @bullet 22039@item Procedure with no formal parameters (returns @code{0} upon 22040normal completion) 22041 22042@item Procedure with no formal parameters (returns @code{42} when 22043an unhandled exception is raised) 22044 22045@item Function with no formal parameters whose returned value 22046is of a discrete type 22047 22048@item Procedure with one @code{out} formal of a discrete type for 22049which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given. 22050 22051@end itemize 22052 22053@noindent 22054When declared with the pragma @code{EXPORT_VALUED_PROCEDURE}, 22055a main function or main procedure returns a discrete 22056value whose size is less than 64 bits (32 on VAX systems), 22057the value is zero- or sign-extended as appropriate. 22058On GNAT, main programs are defined as follows: 22059@itemize @bullet 22060@item Must be a non-generic, parameterless subprogram that 22061is either a procedure or function returning an Ada 22062@code{STANDARD.INTEGER} (the predefined type) 22063 22064@item Cannot be a generic subprogram or an instantiation of a 22065generic subprogram 22066@end itemize 22067 22068@node Implementation-Defined Attributes 22069@section Implementation-Defined Attributes 22070 22071@noindent 22072GNAT provides all HP Ada implementation-defined 22073attributes. 22074 22075@node Compiler and Run-Time Interfacing 22076@section Compiler and Run-Time Interfacing 22077 22078@noindent 22079HP Ada provides the following qualifiers to pass options to the linker 22080(ACS LINK): 22081@itemize @bullet 22082@item @option{/WAIT} and @option{/SUBMIT} 22083 22084@item @option{/COMMAND} 22085 22086@item @option{/@r{[}NO@r{]}MAP} 22087 22088@item @option{/OUTPUT=@var{file-spec}} 22089 22090@item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK} 22091@end itemize 22092 22093@noindent 22094To pass options to the linker, GNAT provides the following 22095switches: 22096 22097@itemize @bullet 22098@item @option{/EXECUTABLE=@var{exec-name}} 22099 22100@item @option{/VERBOSE} 22101 22102@item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK} 22103@end itemize 22104 22105@noindent 22106For more information on these switches, see 22107@ref{Switches for gnatlink}. 22108In HP Ada, the command-line switch @option{/OPTIMIZE} is available 22109to control optimization. HP Ada also supplies the 22110following pragmas: 22111@itemize @bullet 22112@item @code{OPTIMIZE} 22113 22114@item @code{INLINE} 22115 22116@item @code{INLINE_GENERIC} 22117 22118@item @code{SUPPRESS_ALL} 22119 22120@item @code{PASSIVE} 22121@end itemize 22122 22123@noindent 22124In GNAT, optimization is controlled strictly by command 22125line parameters, as described in the corresponding section of this guide. 22126The HP pragmas for control of optimization are 22127recognized but ignored. 22128 22129Note that in GNAT, the default is optimization off, whereas in HP Ada 22130the default is that optimization is turned on. 22131 22132@node Program Compilation and Library Management 22133@section Program Compilation and Library Management 22134 22135@noindent 22136HP Ada and GNAT provide a comparable set of commands to 22137build programs. HP Ada also provides a program library, 22138which is a concept that does not exist on GNAT. Instead, 22139GNAT provides directories of sources that are compiled as 22140needed. 22141 22142The following table summarizes 22143the HP Ada commands and provides 22144equivalent GNAT commands. In this table, some GNAT 22145equivalents reflect the fact that GNAT does not use the 22146concept of a program library. Instead, it uses a model 22147in which collections of source and object files are used 22148in a manner consistent with other languages like C and 22149Fortran. Therefore, standard system file commands are used 22150to manipulate these elements. Those GNAT commands are marked with 22151an asterisk. 22152Note that, unlike HP Ada, none of the GNAT commands accepts wild cards. 22153 22154@need 1500 22155@multitable @columnfractions .35 .65 22156 22157@item @emph{HP Ada Command} 22158@tab @emph{GNAT Equivalent / Description} 22159 22160@item @command{ADA} 22161@tab @command{GNAT COMPILE}@* 22162Invokes the compiler to compile one or more Ada source files. 22163 22164@item @command{ACS ATTACH}@* 22165@tab [No equivalent]@* 22166Switches control of terminal from current process running the program 22167library manager. 22168 22169@item @command{ACS CHECK} 22170@tab @command{GNAT MAKE /DEPENDENCY_LIST}@* 22171Forms the execution closure of one 22172or more compiled units and checks completeness and currency. 22173 22174@item @command{ACS COMPILE} 22175@tab @command{GNAT MAKE /ACTIONS=COMPILE}@* 22176Forms the execution closure of one or 22177more specified units, checks completeness and currency, 22178identifies units that have revised source files, compiles same, 22179and recompiles units that are or will become obsolete. 22180Also completes incomplete generic instantiations. 22181 22182@item @command{ACS COPY FOREIGN} 22183@tab Copy (*)@* 22184Copies a foreign object file into the program library as a 22185library unit body. 22186 22187@item @command{ACS COPY UNIT} 22188@tab Copy (*)@* 22189Copies a compiled unit from one program library to another. 22190 22191@item @command{ACS CREATE LIBRARY} 22192@tab Create /directory (*)@* 22193Creates a program library. 22194 22195@item @command{ACS CREATE SUBLIBRARY} 22196@tab Create /directory (*)@* 22197Creates a program sublibrary. 22198 22199@item @command{ACS DELETE LIBRARY} 22200@tab @* 22201Deletes a program library and its contents. 22202 22203@item @command{ACS DELETE SUBLIBRARY} 22204@tab @* 22205Deletes a program sublibrary and its contents. 22206 22207@item @command{ACS DELETE UNIT} 22208@tab Delete file (*)@* 22209On OpenVMS systems, deletes one or more compiled units from 22210the current program library. 22211 22212@item @command{ACS DIRECTORY} 22213@tab Directory (*)@* 22214On OpenVMS systems, lists units contained in the current 22215program library. 22216 22217@item @command{ACS ENTER FOREIGN} 22218@tab Copy (*)@* 22219Allows the import of a foreign body as an Ada library 22220spec and enters a reference to a pointer. 22221 22222@item @command{ACS ENTER UNIT} 22223@tab Copy (*)@* 22224Enters a reference (pointer) from the current program library to 22225a unit compiled into another program library. 22226 22227@item @command{ACS EXIT} 22228@tab [No equivalent]@* 22229Exits from the program library manager. 22230 22231@item @command{ACS EXPORT} 22232@tab Copy (*)@* 22233Creates an object file that contains system-specific object code 22234for one or more units. With GNAT, object files can simply be copied 22235into the desired directory. 22236 22237@item @command{ACS EXTRACT SOURCE} 22238@tab Copy (*)@* 22239Allows access to the copied source file for each Ada compilation unit 22240 22241@item @command{ACS HELP} 22242@tab @command{HELP GNAT}@* 22243Provides online help. 22244 22245@item @command{ACS LINK} 22246@tab @command{GNAT LINK}@* 22247Links an object file containing Ada units into an executable file. 22248 22249@item @command{ACS LOAD} 22250@tab Copy (*)@* 22251Loads (partially compiles) Ada units into the program library. 22252Allows loading a program from a collection of files into a library 22253without knowing the relationship among units. 22254 22255@item @command{ACS MERGE} 22256@tab Copy (*)@* 22257Merges into the current program library, one or more units from 22258another library where they were modified. 22259 22260@item @command{ACS RECOMPILE} 22261@tab @command{GNAT MAKE /ACTIONS=COMPILE}@* 22262Recompiles from external or copied source files any obsolete 22263unit in the closure. Also, completes any incomplete generic 22264instantiations. 22265 22266@item @command{ACS REENTER} 22267@tab @command{GNAT MAKE}@* 22268Reenters current references to units compiled after last entered 22269with the @command{ACS ENTER UNIT} command. 22270 22271@item @command{ACS SET LIBRARY} 22272@tab Set default (*)@* 22273Defines a program library to be the compilation context as well 22274as the target library for compiler output and commands in general. 22275 22276@item @command{ACS SET PRAGMA} 22277@tab Edit @file{gnat.adc} (*)@* 22278Redefines specified values of the library characteristics 22279@code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME}, 22280and @code{Float_Representation}. 22281 22282@item @command{ACS SET SOURCE} 22283@tab Define @code{ADA_INCLUDE_PATH} path (*)@* 22284Defines the source file search list for the @command{ACS COMPILE} command. 22285 22286@item @command{ACS SHOW LIBRARY} 22287@tab Directory (*)@* 22288Lists information about one or more program libraries. 22289 22290@item @command{ACS SHOW PROGRAM} 22291@tab [No equivalent]@* 22292Lists information about the execution closure of one or 22293more units in the program library. 22294 22295@item @command{ACS SHOW SOURCE} 22296@tab Show logical @code{ADA_INCLUDE_PATH}@* 22297Shows the source file search used when compiling units. 22298 22299@item @command{ACS SHOW VERSION} 22300@tab Compile with @option{VERBOSE} option 22301Displays the version number of the compiler and program library 22302manager used. 22303 22304@item @command{ACS SPAWN} 22305@tab [No equivalent]@* 22306Creates a subprocess of the current process (same as @command{DCL SPAWN} 22307command). 22308 22309@item @command{ACS VERIFY} 22310@tab [No equivalent]@* 22311Performs a series of consistency checks on a program library to 22312determine whether the library structure and library files are in 22313valid form. 22314@end multitable 22315 22316@noindent 22317 22318@node Input-Output 22319@section Input-Output 22320 22321@noindent 22322On OpenVMS Alpha systems, HP Ada uses OpenVMS Record 22323Management Services (RMS) to perform operations on 22324external files. 22325 22326@noindent 22327HP Ada and GNAT predefine an identical set of input- 22328output packages. To make the use of the 22329generic @code{TEXT_IO} operations more convenient, HP Ada 22330provides predefined library packages that instantiate the 22331integer and floating-point operations for the predefined 22332integer and floating-point types as shown in the following table. 22333 22334@multitable @columnfractions .45 .55 22335@item @emph{Package Name} @tab Instantiation 22336 22337@item @code{INTEGER_TEXT_IO} 22338@tab @code{INTEGER_IO(INTEGER)} 22339 22340@item @code{SHORT_INTEGER_TEXT_IO} 22341@tab @code{INTEGER_IO(SHORT_INTEGER)} 22342 22343@item @code{SHORT_SHORT_INTEGER_TEXT_IO} 22344@tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)} 22345 22346@item @code{FLOAT_TEXT_IO} 22347@tab @code{FLOAT_IO(FLOAT)} 22348 22349@item @code{LONG_FLOAT_TEXT_IO} 22350@tab @code{FLOAT_IO(LONG_FLOAT)} 22351@end multitable 22352 22353@noindent 22354The HP Ada predefined packages and their operations 22355are implemented using OpenVMS Alpha files and input-output 22356facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha. 22357Familiarity with the following is recommended: 22358@itemize @bullet 22359@item RMS file organizations and access methods 22360 22361@item OpenVMS file specifications and directories 22362 22363@item OpenVMS File Definition Language (FDL) 22364@end itemize 22365 22366@noindent 22367GNAT provides I/O facilities that are completely 22368compatible with HP Ada. The distribution includes the 22369standard HP Ada versions of all I/O packages, operating 22370in a manner compatible with HP Ada. In particular, the 22371following packages are by default the HP Ada (Ada 83) 22372versions of these packages rather than the renamings 22373suggested in Annex J of the Ada Reference Manual: 22374@itemize @bullet 22375@item @code{TEXT_IO} 22376 22377@item @code{SEQUENTIAL_IO} 22378 22379@item @code{DIRECT_IO} 22380@end itemize 22381 22382@noindent 22383The use of the standard child package syntax (for 22384example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these 22385packages. 22386GNAT provides HP-compatible predefined instantiations 22387of the @code{TEXT_IO} packages, and also 22388provides the standard predefined instantiations required 22389by the @cite{Ada Reference Manual}. 22390 22391For further information on how GNAT interfaces to the file 22392system or how I/O is implemented in programs written in 22393mixed languages, see @ref{Implementation of the Standard I/O,,, 22394gnat_rm, GNAT Reference Manual}. 22395This chapter covers the following: 22396@itemize @bullet 22397@item Standard I/O packages 22398 22399@item @code{FORM} strings 22400 22401@item @code{ADA.DIRECT_IO} 22402 22403@item @code{ADA.SEQUENTIAL_IO} 22404 22405@item @code{ADA.TEXT_IO} 22406 22407@item Stream pointer positioning 22408 22409@item Reading and writing non-regular files 22410 22411@item @code{GET_IMMEDIATE} 22412 22413@item Treating @code{TEXT_IO} files as streams 22414 22415@item Shared files 22416 22417@item Open modes 22418@end itemize 22419 22420@node Implementation Limits 22421@section Implementation Limits 22422 22423@noindent 22424The following table lists implementation limits for HP Ada 22425and GNAT systems. 22426@multitable @columnfractions .60 .20 .20 22427@sp 1 22428@item @emph{Compilation Parameter} 22429@tab @emph{HP Ada} 22430@tab @emph{GNAT} 22431@sp 1 22432 22433@item In a subprogram or entry declaration, maximum number of 22434formal parameters that are of an unconstrained record type 22435@tab 32 22436@tab No set limit 22437@sp 1 22438 22439@item Maximum identifier length (number of characters) 22440@tab 255 22441@tab 32766 22442@sp 1 22443 22444@item Maximum number of characters in a source line 22445@tab 255 22446@tab 32766 22447@sp 1 22448 22449@item Maximum collection size (number of bytes) 22450@tab 2**31-1 22451@tab 2**31-1 22452@sp 1 22453 22454@item Maximum number of discriminants for a record type 22455@tab 245 22456@tab No set limit 22457@sp 1 22458 22459@item Maximum number of formal parameters in an entry or 22460subprogram declaration 22461@tab 246 22462@tab No set limit 22463@sp 1 22464 22465@item Maximum number of dimensions in an array type 22466@tab 255 22467@tab No set limit 22468@sp 1 22469 22470@item Maximum number of library units and subunits in a compilation. 22471@tab 4095 22472@tab No set limit 22473@sp 1 22474 22475@item Maximum number of library units and subunits in an execution. 22476@tab 16383 22477@tab No set limit 22478@sp 1 22479 22480@item Maximum number of objects declared with the pragma @code{COMMON_OBJECT} 22481or @code{PSECT_OBJECT} 22482@tab 32757 22483@tab No set limit 22484@sp 1 22485 22486@item Maximum number of enumeration literals in an enumeration type 22487definition 22488@tab 65535 22489@tab No set limit 22490@sp 1 22491 22492@item Maximum number of lines in a source file 22493@tab 65534 22494@tab No set limit 22495@sp 1 22496 22497@item Maximum number of bits in any object 22498@tab 2**31-1 22499@tab 2**31-1 22500@sp 1 22501 22502@item Maximum size of the static portion of a stack frame (approximate) 22503@tab 2**31-1 22504@tab 2**31-1 22505@end multitable 22506 22507@node Tools and Utilities 22508@section Tools and Utilities 22509 22510@noindent 22511The following table lists some of the OpenVMS development tools 22512available for HP Ada, and the corresponding tools for 22513use with @value{EDITION} on Alpha and I64 platforms. 22514Aside from the debugger, all the OpenVMS tools identified are part 22515of the DECset package. 22516 22517@iftex 22518@c Specify table in TeX since Texinfo does a poor job 22519@tex 22520\smallskip 22521\smallskip 22522\settabs\+Language-Sensitive Editor\quad 22523 &Product with HP Ada\quad 22524 &\cr 22525\+\it Tool 22526 &\it Product with HP Ada 22527 & \it Product with @value{EDITION}\cr 22528\smallskip 22529\+Code Management System 22530 &HP CMS 22531 & HP CMS\cr 22532\smallskip 22533\+Language-Sensitive Editor 22534 &HP LSE 22535 & emacs or HP LSE (Alpha)\cr 22536\+ 22537 & 22538 & HP LSE (I64)\cr 22539\smallskip 22540\+Debugger 22541 &OpenVMS Debug 22542 & gdb (Alpha),\cr 22543\+ 22544 & 22545 & OpenVMS Debug (I64)\cr 22546\smallskip 22547\+Source Code Analyzer / 22548 &HP SCA 22549 & GNAT XREF\cr 22550\+Cross Referencer 22551 & 22552 &\cr 22553\smallskip 22554\+Test Manager 22555 &HP Digital Test 22556 & HP DTM\cr 22557\+ 22558 &Manager (DTM) 22559 &\cr 22560\smallskip 22561\+Performance and 22562 & HP PCA 22563 & HP PCA\cr 22564\+Coverage Analyzer 22565 & 22566 &\cr 22567\smallskip 22568\+Module Management 22569 & HP MMS 22570 & Not applicable\cr 22571\+ System 22572 & 22573 &\cr 22574\smallskip 22575\smallskip 22576@end tex 22577@end iftex 22578 22579@ifnottex 22580@c This is the Texinfo version of the table. It renders poorly in pdf, hence 22581@c the TeX version above for the printed version 22582@flushleft 22583@c @multitable @columnfractions .3 .4 .4 22584@multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}} 22585@item @i{Tool} 22586@tab @i{Tool with HP Ada} 22587@tab @i{Tool with @value{EDITION}} 22588@item Code Management@*System 22589@tab HP CMS 22590@tab HP CMS 22591@item Language-Sensitive@*Editor 22592@tab HP LSE 22593@tab emacs or HP LSE (Alpha) 22594@item 22595@tab 22596@tab HP LSE (I64) 22597@item Debugger 22598@tab OpenVMS Debug 22599@tab gdb (Alpha), 22600@item 22601@tab 22602@tab OpenVMS Debug (I64) 22603@item Source Code Analyzer /@*Cross Referencer 22604@tab HP SCA 22605@tab GNAT XREF 22606@item Test Manager 22607@tab HP Digital Test@*Manager (DTM) 22608@tab HP DTM 22609@item Performance and@*Coverage Analyzer 22610@tab HP PCA 22611@tab HP PCA 22612@item Module Management@*System 22613@tab HP MMS 22614@tab Not applicable 22615@end multitable 22616@end flushleft 22617@end ifnottex 22618 22619@end ifset 22620 22621@c ************************************** 22622@node Platform-Specific Information for the Run-Time Libraries 22623@appendix Platform-Specific Information for the Run-Time Libraries 22624@cindex Tasking and threads libraries 22625@cindex Threads libraries and tasking 22626@cindex Run-time libraries (platform-specific information) 22627 22628@noindent 22629The GNAT run-time implementation may vary with respect to both the 22630underlying threads library and the exception handling scheme. 22631For threads support, one or more of the following are supplied: 22632@itemize @bullet 22633@item @b{native threads library}, a binding to the thread package from 22634the underlying operating system 22635 22636@item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris 22637POSIX thread package 22638@end itemize 22639 22640@noindent 22641For exception handling, either or both of two models are supplied: 22642@itemize @bullet 22643@item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{ 22644Most programs should experience a substantial speed improvement by 22645being compiled with a ZCX run-time. 22646This is especially true for 22647tasking applications or applications with many exception handlers.} 22648@cindex Zero-Cost Exceptions 22649@cindex ZCX (Zero-Cost Exceptions) 22650which uses binder-generated tables that 22651are interrogated at run time to locate a handler 22652 22653@item @b{setjmp / longjmp} (``SJLJ''), 22654@cindex setjmp/longjmp Exception Model 22655@cindex SJLJ (setjmp/longjmp Exception Model) 22656which uses dynamically-set data to establish 22657the set of handlers 22658@end itemize 22659 22660@noindent 22661This appendix summarizes which combinations of threads and exception support 22662are supplied on various GNAT platforms. 22663It then shows how to select a particular library either 22664permanently or temporarily, 22665explains the properties of (and tradeoffs among) the various threads 22666libraries, and provides some additional 22667information about several specific platforms. 22668 22669@menu 22670* Summary of Run-Time Configurations:: 22671* Specifying a Run-Time Library:: 22672* Choosing the Scheduling Policy:: 22673* Solaris-Specific Considerations:: 22674* Linux-Specific Considerations:: 22675* AIX-Specific Considerations:: 22676* RTX-Specific Considerations:: 22677* HP-UX-Specific Considerations:: 22678@end menu 22679 22680@node Summary of Run-Time Configurations 22681@section Summary of Run-Time Configurations 22682 22683@multitable @columnfractions .30 .70 22684@item @b{alpha-openvms} 22685@item @code{@ @ }@i{rts-native (default)} 22686@item @code{@ @ @ @ }Tasking @tab native VMS threads 22687@item @code{@ @ @ @ }Exceptions @tab ZCX 22688@* 22689@item @code{@ @ }@i{rts-sjlj} 22690@item @code{@ @ @ @ }Tasking @tab native TRU64 threads 22691@item @code{@ @ @ @ }Exceptions @tab SJLJ 22692@* 22693@item @b{ia64-hp_linux} 22694@item @code{@ @ }@i{rts-native (default)} 22695@item @code{@ @ @ @ }Tasking @tab pthread library 22696@item @code{@ @ @ @ }Exceptions @tab ZCX 22697@* 22698@item @b{ia64-hpux} 22699@item @code{@ @ }@i{rts-native (default)} 22700@item @code{@ @ @ @ }Tasking @tab native HP-UX threads 22701@item @code{@ @ @ @ }Exceptions @tab SJLJ 22702@* 22703@item @b{ia64-openvms} 22704@item @code{@ @ }@i{rts-native (default)} 22705@item @code{@ @ @ @ }Tasking @tab native VMS threads 22706@item @code{@ @ @ @ }Exceptions @tab ZCX 22707@* 22708@item @b{ia64-sgi_linux} 22709@item @code{@ @ }@i{rts-native (default)} 22710@item @code{@ @ @ @ }Tasking @tab pthread library 22711@item @code{@ @ @ @ }Exceptions @tab ZCX 22712@* 22713@item @b{pa-hpux} 22714@item @code{@ @ }@i{rts-native (default)} 22715@item @code{@ @ @ @ }Tasking @tab native HP-UX threads 22716@item @code{@ @ @ @ }Exceptions @tab ZCX 22717@* 22718@item @code{@ @ }@i{rts-sjlj} 22719@item @code{@ @ @ @ }Tasking @tab native HP-UX threads 22720@item @code{@ @ @ @ }Exceptions @tab SJLJ 22721@* 22722@item @b{ppc-aix} 22723@item @code{@ @ }@i{rts-native (default)} 22724@item @code{@ @ @ @ }Tasking @tab native AIX threads 22725@item @code{@ @ @ @ }Exceptions @tab ZCX 22726@* 22727@item @code{@ @ }@i{rts-sjlj} 22728@item @code{@ @ @ @ }Tasking @tab native AIX threads 22729@item @code{@ @ @ @ }Exceptions @tab SJLJ 22730@* 22731@item @b{ppc-darwin} 22732@item @code{@ @ }@i{rts-native (default)} 22733@item @code{@ @ @ @ }Tasking @tab native MacOS threads 22734@item @code{@ @ @ @ }Exceptions @tab ZCX 22735@* 22736@item @b{sparc-solaris} @tab 22737@item @code{@ @ }@i{rts-native (default)} 22738@item @code{@ @ @ @ }Tasking @tab native Solaris threads library 22739@item @code{@ @ @ @ }Exceptions @tab ZCX 22740@* 22741@item @code{@ @ }@i{rts-pthread} 22742@item @code{@ @ @ @ }Tasking @tab pthread library 22743@item @code{@ @ @ @ }Exceptions @tab ZCX 22744@* 22745@item @code{@ @ }@i{rts-sjlj} 22746@item @code{@ @ @ @ }Tasking @tab native Solaris threads library 22747@item @code{@ @ @ @ }Exceptions @tab SJLJ 22748@* 22749@item @b{sparc64-solaris} @tab 22750@item @code{@ @ }@i{rts-native (default)} 22751@item @code{@ @ @ @ }Tasking @tab native Solaris threads library 22752@item @code{@ @ @ @ }Exceptions @tab ZCX 22753@* 22754@item @b{x86-linux} 22755@item @code{@ @ }@i{rts-native (default)} 22756@item @code{@ @ @ @ }Tasking @tab pthread library 22757@item @code{@ @ @ @ }Exceptions @tab ZCX 22758@* 22759@item @code{@ @ }@i{rts-sjlj} 22760@item @code{@ @ @ @ }Tasking @tab pthread library 22761@item @code{@ @ @ @ }Exceptions @tab SJLJ 22762@* 22763@item @b{x86-lynx} 22764@item @code{@ @ }@i{rts-native (default)} 22765@item @code{@ @ @ @ }Tasking @tab native LynxOS threads 22766@item @code{@ @ @ @ }Exceptions @tab SJLJ 22767@* 22768@item @b{x86-solaris} 22769@item @code{@ @ }@i{rts-native (default)} 22770@item @code{@ @ @ @ }Tasking @tab native Solaris threads 22771@item @code{@ @ @ @ }Exceptions @tab ZCX 22772@* 22773@item @code{@ @ }@i{rts-sjlj} 22774@item @code{@ @ @ @ }Tasking @tab native Solaris threads library 22775@item @code{@ @ @ @ }Exceptions @tab SJLJ 22776@* 22777@item @b{x86-windows} 22778@item @code{@ @ }@i{rts-native (default)} 22779@item @code{@ @ @ @ }Tasking @tab native Win32 threads 22780@item @code{@ @ @ @ }Exceptions @tab ZCX 22781@* 22782@item @code{@ @ }@i{rts-sjlj} 22783@item @code{@ @ @ @ }Tasking @tab native Win32 threads 22784@item @code{@ @ @ @ }Exceptions @tab SJLJ 22785@* 22786@item @b{x86-windows-rtx} 22787@item @code{@ @ }@i{rts-rtx-rtss (default)} 22788@item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode) 22789@item @code{@ @ @ @ }Exceptions @tab SJLJ 22790@* 22791@item @code{@ @ }@i{rts-rtx-w32} 22792@item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode) 22793@item @code{@ @ @ @ }Exceptions @tab ZCX 22794@* 22795@item @b{x86_64-linux} 22796@item @code{@ @ }@i{rts-native (default)} 22797@item @code{@ @ @ @ }Tasking @tab pthread library 22798@item @code{@ @ @ @ }Exceptions @tab ZCX 22799@* 22800@item @code{@ @ }@i{rts-sjlj} 22801@item @code{@ @ @ @ }Tasking @tab pthread library 22802@item @code{@ @ @ @ }Exceptions @tab SJLJ 22803@* 22804@end multitable 22805 22806@node Specifying a Run-Time Library 22807@section Specifying a Run-Time Library 22808 22809@noindent 22810The @file{adainclude} subdirectory containing the sources of the GNAT 22811run-time library, and the @file{adalib} subdirectory containing the 22812@file{ALI} files and the static and/or shared GNAT library, are located 22813in the gcc target-dependent area: 22814 22815@smallexample 22816target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/ 22817@end smallexample 22818 22819@noindent 22820As indicated above, on some platforms several run-time libraries are supplied. 22821These libraries are installed in the target dependent area and 22822contain a complete source and binary subdirectory. The detailed description 22823below explains the differences between the different libraries in terms of 22824their thread support. 22825 22826The default run-time library (when GNAT is installed) is @emph{rts-native}. 22827This default run time is selected by the means of soft links. 22828For example on x86-linux: 22829 22830@smallexample 22831@group 22832 $(target-dir) 22833 | 22834 +--- adainclude----------+ 22835 | | 22836 +--- adalib-----------+ | 22837 | | | 22838 +--- rts-native | | 22839 | | | | 22840 | +--- adainclude <---+ 22841 | | | 22842 | +--- adalib <----+ 22843 | 22844 +--- rts-sjlj 22845 | 22846 +--- adainclude 22847 | 22848 +--- adalib 22849@end group 22850@end smallexample 22851 22852@noindent 22853If the @i{rts-sjlj} library is to be selected on a permanent basis, 22854these soft links can be modified with the following commands: 22855 22856@smallexample 22857$ cd $target 22858$ rm -f adainclude adalib 22859$ ln -s rts-sjlj/adainclude adainclude 22860$ ln -s rts-sjlj/adalib adalib 22861@end smallexample 22862 22863@noindent 22864Alternatively, you can specify @file{rts-sjlj/adainclude} in the file 22865@file{$target/ada_source_path} and @file{rts-sjlj/adalib} in 22866@file{$target/ada_object_path}. 22867 22868Selecting another run-time library temporarily can be 22869achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj} 22870@cindex @option{--RTS} option 22871 22872@node Choosing the Scheduling Policy 22873@section Choosing the Scheduling Policy 22874 22875@noindent 22876When using a POSIX threads implementation, you have a choice of several 22877scheduling policies: @code{SCHED_FIFO}, 22878@cindex @code{SCHED_FIFO} scheduling policy 22879@code{SCHED_RR} 22880@cindex @code{SCHED_RR} scheduling policy 22881and @code{SCHED_OTHER}. 22882@cindex @code{SCHED_OTHER} scheduling policy 22883Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO} 22884or @code{SCHED_RR} requires special (e.g., root) privileges. 22885 22886By default, GNAT uses the @code{SCHED_OTHER} policy. To specify 22887@code{SCHED_FIFO}, 22888@cindex @code{SCHED_FIFO} scheduling policy 22889you can use one of the following: 22890 22891@itemize @bullet 22892@item 22893@code{pragma Time_Slice (0.0)} 22894@cindex pragma Time_Slice 22895@item 22896the corresponding binder option @option{-T0} 22897@cindex @option{-T0} option 22898@item 22899@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)} 22900@cindex pragma Task_Dispatching_Policy 22901@end itemize 22902 22903@noindent 22904To specify @code{SCHED_RR}, 22905@cindex @code{SCHED_RR} scheduling policy 22906you should use @code{pragma Time_Slice} with a 22907value greater than @code{0.0}, or else use the corresponding @option{-T} 22908binder option. 22909 22910@node Solaris-Specific Considerations 22911@section Solaris-Specific Considerations 22912@cindex Solaris Sparc threads libraries 22913 22914@noindent 22915This section addresses some topics related to the various threads libraries 22916on Sparc Solaris. 22917 22918@menu 22919* Solaris Threads Issues:: 22920@end menu 22921 22922@node Solaris Threads Issues 22923@subsection Solaris Threads Issues 22924 22925@noindent 22926GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time 22927library based on POSIX threads --- @emph{rts-pthread}. 22928@cindex rts-pthread threads library 22929This run-time library has the advantage of being mostly shared across all 22930POSIX-compliant thread implementations, and it also provides under 22931@w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT} 22932@cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread) 22933and @code{PTHREAD_PRIO_PROTECT} 22934@cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread) 22935semantics that can be selected using the predefined pragma 22936@code{Locking_Policy} 22937@cindex pragma Locking_Policy (under rts-pthread) 22938with respectively 22939@code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy. 22940@cindex @code{Inheritance_Locking} (under rts-pthread) 22941@cindex @code{Ceiling_Locking} (under rts-pthread) 22942 22943As explained above, the native run-time library is based on the Solaris thread 22944library (@code{libthread}) and is the default library. 22945 22946When the Solaris threads library is used (this is the default), programs 22947compiled with GNAT can automatically take advantage of 22948and can thus execute on multiple processors. 22949The user can alternatively specify a processor on which the program should run 22950to emulate a single-processor system. The multiprocessor / uniprocessor choice 22951is made by 22952setting the environment variable @env{GNAT_PROCESSOR} 22953@cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris) 22954to one of the following: 22955 22956@table @code 22957@item -2 22958Use the default configuration (run the program on all 22959available processors) - this is the same as having @code{GNAT_PROCESSOR} 22960unset 22961 22962@item -1 22963Let the run-time implementation choose one processor and run the program on 22964that processor 22965 22966@item 0 .. Last_Proc 22967Run the program on the specified processor. 22968@code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1} 22969(where @code{_SC_NPROCESSORS_CONF} is a system variable). 22970@end table 22971 22972@node Linux-Specific Considerations 22973@section Linux-Specific Considerations 22974@cindex Linux threads libraries 22975 22976@noindent 22977On GNU/Linux without NPTL support (usually system with GNU C Library 22978older than 2.3), the signal model is not POSIX compliant, which means 22979that to send a signal to the process, you need to send the signal to all 22980threads, e.g.@: by using @code{killpg()}. 22981 22982@node AIX-Specific Considerations 22983@section AIX-Specific Considerations 22984@cindex AIX resolver library 22985 22986@noindent 22987On AIX, the resolver library initializes some internal structure on 22988the first call to @code{get*by*} functions, which are used to implement 22989@code{GNAT.Sockets.Get_Host_By_Name} and 22990@code{GNAT.Sockets.Get_Host_By_Address}. 22991If such initialization occurs within an Ada task, and the stack size for 22992the task is the default size, a stack overflow may occur. 22993 22994To avoid this overflow, the user should either ensure that the first call 22995to @code{GNAT.Sockets.Get_Host_By_Name} or 22996@code{GNAT.Sockets.Get_Host_By_Addrss} 22997occurs in the environment task, or use @code{pragma Storage_Size} to 22998specify a sufficiently large size for the stack of the task that contains 22999this call. 23000 23001@node RTX-Specific Considerations 23002@section RTX-Specific Considerations 23003@cindex RTX libraries 23004 23005@noindent 23006The Real-time Extension (RTX) to Windows is based on the Windows Win32 23007API. Applications can be built to work in two different modes: 23008 23009@itemize @bullet 23010@item 23011Windows executables that run in Ring 3 to utilize memory protection 23012(@emph{rts-rtx-w32}). 23013 23014@item 23015Real-time subsystem (RTSS) executables that run in Ring 0, where 23016performance can be optimized with RTSS applications taking precedent 23017over all Windows applications (@emph{rts-rtx-rtss}). This mode requires 23018the Microsoft linker to handle RTSS libraries. 23019 23020@end itemize 23021 23022@node HP-UX-Specific Considerations 23023@section HP-UX-Specific Considerations 23024@cindex HP-UX Scheduling 23025 23026@noindent 23027On HP-UX, appropriate privileges are required to change the scheduling 23028parameters of a task. The calling process must have appropriate 23029privileges or be a member of a group having @code{PRIV_RTSCHED} access to 23030successfully change the scheduling parameters. 23031 23032By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the 23033priority range 0-31 either the @code{FIFO_Within_Priorities} or the 23034@code{Round_Robin_Within_Priorities} scheduling policies need to be set. 23035 23036To specify the @code{FIFO_Within_Priorities} scheduling policy you can use 23037one of the following: 23038 23039@itemize @bullet 23040@item 23041@code{pragma Time_Slice (0.0)} 23042@cindex pragma Time_Slice 23043@item 23044the corresponding binder option @option{-T0} 23045@cindex @option{-T0} option 23046@item 23047@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)} 23048@cindex pragma Task_Dispatching_Policy 23049@end itemize 23050 23051@noindent 23052To specify the @code{Round_Robin_Within_Priorities}, scheduling policy 23053you should use @code{pragma Time_Slice} with a 23054value greater than @code{0.0}, or use the corresponding @option{-T} 23055binder option, or set the @code{pragma Task_Dispatching_Policy 23056(Round_Robin_Within_Priorities)}. 23057 23058@c ******************************* 23059@node Example of Binder Output File 23060@appendix Example of Binder Output File 23061 23062@noindent 23063This Appendix displays the source code for @command{gnatbind}'s output 23064file generated for a simple ``Hello World'' program. 23065Comments have been added for clarification purposes. 23066 23067@smallexample @c adanocomment 23068@iftex 23069@leftskip=0cm 23070@end iftex 23071-- The package is called Ada_Main unless this name is actually used 23072-- as a unit name in the partition, in which case some other unique 23073-- name is used. 23074 23075with System; 23076package ada_main is 23077 23078 Elab_Final_Code : Integer; 23079 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code"); 23080 23081 -- The main program saves the parameters (argument count, 23082 -- argument values, environment pointer) in global variables 23083 -- for later access by other units including 23084 -- Ada.Command_Line. 23085 23086 gnat_argc : Integer; 23087 gnat_argv : System.Address; 23088 gnat_envp : System.Address; 23089 23090 -- The actual variables are stored in a library routine. This 23091 -- is useful for some shared library situations, where there 23092 -- are problems if variables are not in the library. 23093 23094 pragma Import (C, gnat_argc); 23095 pragma Import (C, gnat_argv); 23096 pragma Import (C, gnat_envp); 23097 23098 -- The exit status is similarly an external location 23099 23100 gnat_exit_status : Integer; 23101 pragma Import (C, gnat_exit_status); 23102 23103 GNAT_Version : constant String := 23104 "GNAT Version: 6.0.0w (20061115)"; 23105 pragma Export (C, GNAT_Version, "__gnat_version"); 23106 23107 -- This is the generated adafinal routine that performs 23108 -- finalization at the end of execution. In the case where 23109 -- Ada is the main program, this main program makes a call 23110 -- to adafinal at program termination. 23111 23112 procedure adafinal; 23113 pragma Export (C, adafinal, "adafinal"); 23114 23115 -- This is the generated adainit routine that performs 23116 -- initialization at the start of execution. In the case 23117 -- where Ada is the main program, this main program makes 23118 -- a call to adainit at program startup. 23119 23120 procedure adainit; 23121 pragma Export (C, adainit, "adainit"); 23122 23123 -- This routine is called at the start of execution. It is 23124 -- a dummy routine that is used by the debugger to breakpoint 23125 -- at the start of execution. 23126 23127 procedure Break_Start; 23128 pragma Import (C, Break_Start, "__gnat_break_start"); 23129 23130 -- This is the actual generated main program (it would be 23131 -- suppressed if the no main program switch were used). As 23132 -- required by standard system conventions, this program has 23133 -- the external name main. 23134 23135 function main 23136 (argc : Integer; 23137 argv : System.Address; 23138 envp : System.Address) 23139 return Integer; 23140 pragma Export (C, main, "main"); 23141 23142 -- The following set of constants give the version 23143 -- identification values for every unit in the bound 23144 -- partition. This identification is computed from all 23145 -- dependent semantic units, and corresponds to the 23146 -- string that would be returned by use of the 23147 -- Body_Version or Version attributes. 23148 23149 type Version_32 is mod 2 ** 32; 23150 u00001 : constant Version_32 := 16#7880BEB3#; 23151 u00002 : constant Version_32 := 16#0D24CBD0#; 23152 u00003 : constant Version_32 := 16#3283DBEB#; 23153 u00004 : constant Version_32 := 16#2359F9ED#; 23154 u00005 : constant Version_32 := 16#664FB847#; 23155 u00006 : constant Version_32 := 16#68E803DF#; 23156 u00007 : constant Version_32 := 16#5572E604#; 23157 u00008 : constant Version_32 := 16#46B173D8#; 23158 u00009 : constant Version_32 := 16#156A40CF#; 23159 u00010 : constant Version_32 := 16#033DABE0#; 23160 u00011 : constant Version_32 := 16#6AB38FEA#; 23161 u00012 : constant Version_32 := 16#22B6217D#; 23162 u00013 : constant Version_32 := 16#68A22947#; 23163 u00014 : constant Version_32 := 16#18CC4A56#; 23164 u00015 : constant Version_32 := 16#08258E1B#; 23165 u00016 : constant Version_32 := 16#367D5222#; 23166 u00017 : constant Version_32 := 16#20C9ECA4#; 23167 u00018 : constant Version_32 := 16#50D32CB6#; 23168 u00019 : constant Version_32 := 16#39A8BB77#; 23169 u00020 : constant Version_32 := 16#5CF8FA2B#; 23170 u00021 : constant Version_32 := 16#2F1EB794#; 23171 u00022 : constant Version_32 := 16#31AB6444#; 23172 u00023 : constant Version_32 := 16#1574B6E9#; 23173 u00024 : constant Version_32 := 16#5109C189#; 23174 u00025 : constant Version_32 := 16#56D770CD#; 23175 u00026 : constant Version_32 := 16#02F9DE3D#; 23176 u00027 : constant Version_32 := 16#08AB6B2C#; 23177 u00028 : constant Version_32 := 16#3FA37670#; 23178 u00029 : constant Version_32 := 16#476457A0#; 23179 u00030 : constant Version_32 := 16#731E1B6E#; 23180 u00031 : constant Version_32 := 16#23C2E789#; 23181 u00032 : constant Version_32 := 16#0F1BD6A1#; 23182 u00033 : constant Version_32 := 16#7C25DE96#; 23183 u00034 : constant Version_32 := 16#39ADFFA2#; 23184 u00035 : constant Version_32 := 16#571DE3E7#; 23185 u00036 : constant Version_32 := 16#5EB646AB#; 23186 u00037 : constant Version_32 := 16#4249379B#; 23187 u00038 : constant Version_32 := 16#0357E00A#; 23188 u00039 : constant Version_32 := 16#3784FB72#; 23189 u00040 : constant Version_32 := 16#2E723019#; 23190 u00041 : constant Version_32 := 16#623358EA#; 23191 u00042 : constant Version_32 := 16#107F9465#; 23192 u00043 : constant Version_32 := 16#6843F68A#; 23193 u00044 : constant Version_32 := 16#63305874#; 23194 u00045 : constant Version_32 := 16#31E56CE1#; 23195 u00046 : constant Version_32 := 16#02917970#; 23196 u00047 : constant Version_32 := 16#6CCBA70E#; 23197 u00048 : constant Version_32 := 16#41CD4204#; 23198 u00049 : constant Version_32 := 16#572E3F58#; 23199 u00050 : constant Version_32 := 16#20729FF5#; 23200 u00051 : constant Version_32 := 16#1D4F93E8#; 23201 u00052 : constant Version_32 := 16#30B2EC3D#; 23202 u00053 : constant Version_32 := 16#34054F96#; 23203 u00054 : constant Version_32 := 16#5A199860#; 23204 u00055 : constant Version_32 := 16#0E7F912B#; 23205 u00056 : constant Version_32 := 16#5760634A#; 23206 u00057 : constant Version_32 := 16#5D851835#; 23207 23208 -- The following Export pragmas export the version numbers 23209 -- with symbolic names ending in B (for body) or S 23210 -- (for spec) so that they can be located in a link. The 23211 -- information provided here is sufficient to track down 23212 -- the exact versions of units used in a given build. 23213 23214 pragma Export (C, u00001, "helloB"); 23215 pragma Export (C, u00002, "system__standard_libraryB"); 23216 pragma Export (C, u00003, "system__standard_libraryS"); 23217 pragma Export (C, u00004, "adaS"); 23218 pragma Export (C, u00005, "ada__text_ioB"); 23219 pragma Export (C, u00006, "ada__text_ioS"); 23220 pragma Export (C, u00007, "ada__exceptionsB"); 23221 pragma Export (C, u00008, "ada__exceptionsS"); 23222 pragma Export (C, u00009, "gnatS"); 23223 pragma Export (C, u00010, "gnat__heap_sort_aB"); 23224 pragma Export (C, u00011, "gnat__heap_sort_aS"); 23225 pragma Export (C, u00012, "systemS"); 23226 pragma Export (C, u00013, "system__exception_tableB"); 23227 pragma Export (C, u00014, "system__exception_tableS"); 23228 pragma Export (C, u00015, "gnat__htableB"); 23229 pragma Export (C, u00016, "gnat__htableS"); 23230 pragma Export (C, u00017, "system__exceptionsS"); 23231 pragma Export (C, u00018, "system__machine_state_operationsB"); 23232 pragma Export (C, u00019, "system__machine_state_operationsS"); 23233 pragma Export (C, u00020, "system__machine_codeS"); 23234 pragma Export (C, u00021, "system__storage_elementsB"); 23235 pragma Export (C, u00022, "system__storage_elementsS"); 23236 pragma Export (C, u00023, "system__secondary_stackB"); 23237 pragma Export (C, u00024, "system__secondary_stackS"); 23238 pragma Export (C, u00025, "system__parametersB"); 23239 pragma Export (C, u00026, "system__parametersS"); 23240 pragma Export (C, u00027, "system__soft_linksB"); 23241 pragma Export (C, u00028, "system__soft_linksS"); 23242 pragma Export (C, u00029, "system__stack_checkingB"); 23243 pragma Export (C, u00030, "system__stack_checkingS"); 23244 pragma Export (C, u00031, "system__tracebackB"); 23245 pragma Export (C, u00032, "system__tracebackS"); 23246 pragma Export (C, u00033, "ada__streamsS"); 23247 pragma Export (C, u00034, "ada__tagsB"); 23248 pragma Export (C, u00035, "ada__tagsS"); 23249 pragma Export (C, u00036, "system__string_opsB"); 23250 pragma Export (C, u00037, "system__string_opsS"); 23251 pragma Export (C, u00038, "interfacesS"); 23252 pragma Export (C, u00039, "interfaces__c_streamsB"); 23253 pragma Export (C, u00040, "interfaces__c_streamsS"); 23254 pragma Export (C, u00041, "system__file_ioB"); 23255 pragma Export (C, u00042, "system__file_ioS"); 23256 pragma Export (C, u00043, "ada__finalizationB"); 23257 pragma Export (C, u00044, "ada__finalizationS"); 23258 pragma Export (C, u00045, "system__finalization_rootB"); 23259 pragma Export (C, u00046, "system__finalization_rootS"); 23260 pragma Export (C, u00047, "system__finalization_implementationB"); 23261 pragma Export (C, u00048, "system__finalization_implementationS"); 23262 pragma Export (C, u00049, "system__string_ops_concat_3B"); 23263 pragma Export (C, u00050, "system__string_ops_concat_3S"); 23264 pragma Export (C, u00051, "system__stream_attributesB"); 23265 pragma Export (C, u00052, "system__stream_attributesS"); 23266 pragma Export (C, u00053, "ada__io_exceptionsS"); 23267 pragma Export (C, u00054, "system__unsigned_typesS"); 23268 pragma Export (C, u00055, "system__file_control_blockS"); 23269 pragma Export (C, u00056, "ada__finalization__list_controllerB"); 23270 pragma Export (C, u00057, "ada__finalization__list_controllerS"); 23271 23272 -- BEGIN ELABORATION ORDER 23273 -- ada (spec) 23274 -- gnat (spec) 23275 -- gnat.heap_sort_a (spec) 23276 -- gnat.heap_sort_a (body) 23277 -- gnat.htable (spec) 23278 -- gnat.htable (body) 23279 -- interfaces (spec) 23280 -- system (spec) 23281 -- system.machine_code (spec) 23282 -- system.parameters (spec) 23283 -- system.parameters (body) 23284 -- interfaces.c_streams (spec) 23285 -- interfaces.c_streams (body) 23286 -- system.standard_library (spec) 23287 -- ada.exceptions (spec) 23288 -- system.exception_table (spec) 23289 -- system.exception_table (body) 23290 -- ada.io_exceptions (spec) 23291 -- system.exceptions (spec) 23292 -- system.storage_elements (spec) 23293 -- system.storage_elements (body) 23294 -- system.machine_state_operations (spec) 23295 -- system.machine_state_operations (body) 23296 -- system.secondary_stack (spec) 23297 -- system.stack_checking (spec) 23298 -- system.soft_links (spec) 23299 -- system.soft_links (body) 23300 -- system.stack_checking (body) 23301 -- system.secondary_stack (body) 23302 -- system.standard_library (body) 23303 -- system.string_ops (spec) 23304 -- system.string_ops (body) 23305 -- ada.tags (spec) 23306 -- ada.tags (body) 23307 -- ada.streams (spec) 23308 -- system.finalization_root (spec) 23309 -- system.finalization_root (body) 23310 -- system.string_ops_concat_3 (spec) 23311 -- system.string_ops_concat_3 (body) 23312 -- system.traceback (spec) 23313 -- system.traceback (body) 23314 -- ada.exceptions (body) 23315 -- system.unsigned_types (spec) 23316 -- system.stream_attributes (spec) 23317 -- system.stream_attributes (body) 23318 -- system.finalization_implementation (spec) 23319 -- system.finalization_implementation (body) 23320 -- ada.finalization (spec) 23321 -- ada.finalization (body) 23322 -- ada.finalization.list_controller (spec) 23323 -- ada.finalization.list_controller (body) 23324 -- system.file_control_block (spec) 23325 -- system.file_io (spec) 23326 -- system.file_io (body) 23327 -- ada.text_io (spec) 23328 -- ada.text_io (body) 23329 -- hello (body) 23330 -- END ELABORATION ORDER 23331 23332end ada_main; 23333 23334-- The following source file name pragmas allow the generated file 23335-- names to be unique for different main programs. They are needed 23336-- since the package name will always be Ada_Main. 23337 23338pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads"); 23339pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb"); 23340 23341-- Generated package body for Ada_Main starts here 23342 23343package body ada_main is 23344 23345 -- The actual finalization is performed by calling the 23346 -- library routine in System.Standard_Library.Adafinal 23347 23348 procedure Do_Finalize; 23349 pragma Import (C, Do_Finalize, "system__standard_library__adafinal"); 23350 23351 ------------- 23352 -- adainit -- 23353 ------------- 23354 23355@findex adainit 23356 procedure adainit is 23357 23358 -- These booleans are set to True once the associated unit has 23359 -- been elaborated. It is also used to avoid elaborating the 23360 -- same unit twice. 23361 23362 E040 : Boolean; 23363 pragma Import (Ada, E040, "interfaces__c_streams_E"); 23364 23365 E008 : Boolean; 23366 pragma Import (Ada, E008, "ada__exceptions_E"); 23367 23368 E014 : Boolean; 23369 pragma Import (Ada, E014, "system__exception_table_E"); 23370 23371 E053 : Boolean; 23372 pragma Import (Ada, E053, "ada__io_exceptions_E"); 23373 23374 E017 : Boolean; 23375 pragma Import (Ada, E017, "system__exceptions_E"); 23376 23377 E024 : Boolean; 23378 pragma Import (Ada, E024, "system__secondary_stack_E"); 23379 23380 E030 : Boolean; 23381 pragma Import (Ada, E030, "system__stack_checking_E"); 23382 23383 E028 : Boolean; 23384 pragma Import (Ada, E028, "system__soft_links_E"); 23385 23386 E035 : Boolean; 23387 pragma Import (Ada, E035, "ada__tags_E"); 23388 23389 E033 : Boolean; 23390 pragma Import (Ada, E033, "ada__streams_E"); 23391 23392 E046 : Boolean; 23393 pragma Import (Ada, E046, "system__finalization_root_E"); 23394 23395 E048 : Boolean; 23396 pragma Import (Ada, E048, "system__finalization_implementation_E"); 23397 23398 E044 : Boolean; 23399 pragma Import (Ada, E044, "ada__finalization_E"); 23400 23401 E057 : Boolean; 23402 pragma Import (Ada, E057, "ada__finalization__list_controller_E"); 23403 23404 E055 : Boolean; 23405 pragma Import (Ada, E055, "system__file_control_block_E"); 23406 23407 E042 : Boolean; 23408 pragma Import (Ada, E042, "system__file_io_E"); 23409 23410 E006 : Boolean; 23411 pragma Import (Ada, E006, "ada__text_io_E"); 23412 23413 -- Set_Globals is a library routine that stores away the 23414 -- value of the indicated set of global values in global 23415 -- variables within the library. 23416 23417 procedure Set_Globals 23418 (Main_Priority : Integer; 23419 Time_Slice_Value : Integer; 23420 WC_Encoding : Character; 23421 Locking_Policy : Character; 23422 Queuing_Policy : Character; 23423 Task_Dispatching_Policy : Character; 23424 Adafinal : System.Address; 23425 Unreserve_All_Interrupts : Integer; 23426 Exception_Tracebacks : Integer); 23427@findex __gnat_set_globals 23428 pragma Import (C, Set_Globals, "__gnat_set_globals"); 23429 23430 -- SDP_Table_Build is a library routine used to build the 23431 -- exception tables. See unit Ada.Exceptions in files 23432 -- a-except.ads/adb for full details of how zero cost 23433 -- exception handling works. This procedure, the call to 23434 -- it, and the two following tables are all omitted if the 23435 -- build is in longjmp/setjmp exception mode. 23436 23437@findex SDP_Table_Build 23438@findex Zero Cost Exceptions 23439 procedure SDP_Table_Build 23440 (SDP_Addresses : System.Address; 23441 SDP_Count : Natural; 23442 Elab_Addresses : System.Address; 23443 Elab_Addr_Count : Natural); 23444 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build"); 23445 23446 -- Table of Unit_Exception_Table addresses. Used for zero 23447 -- cost exception handling to build the top level table. 23448 23449 ST : aliased constant array (1 .. 23) of System.Address := ( 23450 Hello'UET_Address, 23451 Ada.Text_Io'UET_Address, 23452 Ada.Exceptions'UET_Address, 23453 Gnat.Heap_Sort_A'UET_Address, 23454 System.Exception_Table'UET_Address, 23455 System.Machine_State_Operations'UET_Address, 23456 System.Secondary_Stack'UET_Address, 23457 System.Parameters'UET_Address, 23458 System.Soft_Links'UET_Address, 23459 System.Stack_Checking'UET_Address, 23460 System.Traceback'UET_Address, 23461 Ada.Streams'UET_Address, 23462 Ada.Tags'UET_Address, 23463 System.String_Ops'UET_Address, 23464 Interfaces.C_Streams'UET_Address, 23465 System.File_Io'UET_Address, 23466 Ada.Finalization'UET_Address, 23467 System.Finalization_Root'UET_Address, 23468 System.Finalization_Implementation'UET_Address, 23469 System.String_Ops_Concat_3'UET_Address, 23470 System.Stream_Attributes'UET_Address, 23471 System.File_Control_Block'UET_Address, 23472 Ada.Finalization.List_Controller'UET_Address); 23473 23474 -- Table of addresses of elaboration routines. Used for 23475 -- zero cost exception handling to make sure these 23476 -- addresses are included in the top level procedure 23477 -- address table. 23478 23479 EA : aliased constant array (1 .. 23) of System.Address := ( 23480 adainit'Code_Address, 23481 Do_Finalize'Code_Address, 23482 Ada.Exceptions'Elab_Spec'Address, 23483 System.Exceptions'Elab_Spec'Address, 23484 Interfaces.C_Streams'Elab_Spec'Address, 23485 System.Exception_Table'Elab_Body'Address, 23486 Ada.Io_Exceptions'Elab_Spec'Address, 23487 System.Stack_Checking'Elab_Spec'Address, 23488 System.Soft_Links'Elab_Body'Address, 23489 System.Secondary_Stack'Elab_Body'Address, 23490 Ada.Tags'Elab_Spec'Address, 23491 Ada.Tags'Elab_Body'Address, 23492 Ada.Streams'Elab_Spec'Address, 23493 System.Finalization_Root'Elab_Spec'Address, 23494 Ada.Exceptions'Elab_Body'Address, 23495 System.Finalization_Implementation'Elab_Spec'Address, 23496 System.Finalization_Implementation'Elab_Body'Address, 23497 Ada.Finalization'Elab_Spec'Address, 23498 Ada.Finalization.List_Controller'Elab_Spec'Address, 23499 System.File_Control_Block'Elab_Spec'Address, 23500 System.File_Io'Elab_Body'Address, 23501 Ada.Text_Io'Elab_Spec'Address, 23502 Ada.Text_Io'Elab_Body'Address); 23503 23504 -- Start of processing for adainit 23505 23506 begin 23507 23508 -- Call SDP_Table_Build to build the top level procedure 23509 -- table for zero cost exception handling (omitted in 23510 -- longjmp/setjmp mode). 23511 23512 SDP_Table_Build (ST'Address, 23, EA'Address, 23); 23513 23514 -- Call Set_Globals to record various information for 23515 -- this partition. The values are derived by the binder 23516 -- from information stored in the ali files by the compiler. 23517 23518@findex __gnat_set_globals 23519 Set_Globals 23520 (Main_Priority => -1, 23521 -- Priority of main program, -1 if no pragma Priority used 23522 23523 Time_Slice_Value => -1, 23524 -- Time slice from Time_Slice pragma, -1 if none used 23525 23526 WC_Encoding => 'b', 23527 -- Wide_Character encoding used, default is brackets 23528 23529 Locking_Policy => ' ', 23530 -- Locking_Policy used, default of space means not 23531 -- specified, otherwise it is the first character of 23532 -- the policy name. 23533 23534 Queuing_Policy => ' ', 23535 -- Queuing_Policy used, default of space means not 23536 -- specified, otherwise it is the first character of 23537 -- the policy name. 23538 23539 Task_Dispatching_Policy => ' ', 23540 -- Task_Dispatching_Policy used, default of space means 23541 -- not specified, otherwise first character of the 23542 -- policy name. 23543 23544 Adafinal => System.Null_Address, 23545 -- Address of Adafinal routine, not used anymore 23546 23547 Unreserve_All_Interrupts => 0, 23548 -- Set true if pragma Unreserve_All_Interrupts was used 23549 23550 Exception_Tracebacks => 0); 23551 -- Indicates if exception tracebacks are enabled 23552 23553 Elab_Final_Code := 1; 23554 23555 -- Now we have the elaboration calls for all units in the partition. 23556 -- The Elab_Spec and Elab_Body attributes generate references to the 23557 -- implicit elaboration procedures generated by the compiler for 23558 -- each unit that requires elaboration. 23559 23560 if not E040 then 23561 Interfaces.C_Streams'Elab_Spec; 23562 end if; 23563 E040 := True; 23564 if not E008 then 23565 Ada.Exceptions'Elab_Spec; 23566 end if; 23567 if not E014 then 23568 System.Exception_Table'Elab_Body; 23569 E014 := True; 23570 end if; 23571 if not E053 then 23572 Ada.Io_Exceptions'Elab_Spec; 23573 E053 := True; 23574 end if; 23575 if not E017 then 23576 System.Exceptions'Elab_Spec; 23577 E017 := True; 23578 end if; 23579 if not E030 then 23580 System.Stack_Checking'Elab_Spec; 23581 end if; 23582 if not E028 then 23583 System.Soft_Links'Elab_Body; 23584 E028 := True; 23585 end if; 23586 E030 := True; 23587 if not E024 then 23588 System.Secondary_Stack'Elab_Body; 23589 E024 := True; 23590 end if; 23591 if not E035 then 23592 Ada.Tags'Elab_Spec; 23593 end if; 23594 if not E035 then 23595 Ada.Tags'Elab_Body; 23596 E035 := True; 23597 end if; 23598 if not E033 then 23599 Ada.Streams'Elab_Spec; 23600 E033 := True; 23601 end if; 23602 if not E046 then 23603 System.Finalization_Root'Elab_Spec; 23604 end if; 23605 E046 := True; 23606 if not E008 then 23607 Ada.Exceptions'Elab_Body; 23608 E008 := True; 23609 end if; 23610 if not E048 then 23611 System.Finalization_Implementation'Elab_Spec; 23612 end if; 23613 if not E048 then 23614 System.Finalization_Implementation'Elab_Body; 23615 E048 := True; 23616 end if; 23617 if not E044 then 23618 Ada.Finalization'Elab_Spec; 23619 end if; 23620 E044 := True; 23621 if not E057 then 23622 Ada.Finalization.List_Controller'Elab_Spec; 23623 end if; 23624 E057 := True; 23625 if not E055 then 23626 System.File_Control_Block'Elab_Spec; 23627 E055 := True; 23628 end if; 23629 if not E042 then 23630 System.File_Io'Elab_Body; 23631 E042 := True; 23632 end if; 23633 if not E006 then 23634 Ada.Text_Io'Elab_Spec; 23635 end if; 23636 if not E006 then 23637 Ada.Text_Io'Elab_Body; 23638 E006 := True; 23639 end if; 23640 23641 Elab_Final_Code := 0; 23642 end adainit; 23643 23644 -------------- 23645 -- adafinal -- 23646 -------------- 23647 23648@findex adafinal 23649 procedure adafinal is 23650 begin 23651 Do_Finalize; 23652 end adafinal; 23653 23654 ---------- 23655 -- main -- 23656 ---------- 23657 23658 -- main is actually a function, as in the ANSI C standard, 23659 -- defined to return the exit status. The three parameters 23660 -- are the argument count, argument values and environment 23661 -- pointer. 23662 23663@findex Main Program 23664 function main 23665 (argc : Integer; 23666 argv : System.Address; 23667 envp : System.Address) 23668 return Integer 23669 is 23670 -- The initialize routine performs low level system 23671 -- initialization using a standard library routine which 23672 -- sets up signal handling and performs any other 23673 -- required setup. The routine can be found in file 23674 -- a-init.c. 23675 23676@findex __gnat_initialize 23677 procedure initialize; 23678 pragma Import (C, initialize, "__gnat_initialize"); 23679 23680 -- The finalize routine performs low level system 23681 -- finalization using a standard library routine. The 23682 -- routine is found in file a-final.c and in the standard 23683 -- distribution is a dummy routine that does nothing, so 23684 -- really this is a hook for special user finalization. 23685 23686@findex __gnat_finalize 23687 procedure finalize; 23688 pragma Import (C, finalize, "__gnat_finalize"); 23689 23690 -- We get to the main program of the partition by using 23691 -- pragma Import because if we try to with the unit and 23692 -- call it Ada style, then not only do we waste time 23693 -- recompiling it, but also, we don't really know the right 23694 -- switches (e.g.@: identifier character set) to be used 23695 -- to compile it. 23696 23697 procedure Ada_Main_Program; 23698 pragma Import (Ada, Ada_Main_Program, "_ada_hello"); 23699 23700 -- Start of processing for main 23701 23702 begin 23703 -- Save global variables 23704 23705 gnat_argc := argc; 23706 gnat_argv := argv; 23707 gnat_envp := envp; 23708 23709 -- Call low level system initialization 23710 23711 Initialize; 23712 23713 -- Call our generated Ada initialization routine 23714 23715 adainit; 23716 23717 -- This is the point at which we want the debugger to get 23718 -- control 23719 23720 Break_Start; 23721 23722 -- Now we call the main program of the partition 23723 23724 Ada_Main_Program; 23725 23726 -- Perform Ada finalization 23727 23728 adafinal; 23729 23730 -- Perform low level system finalization 23731 23732 Finalize; 23733 23734 -- Return the proper exit status 23735 return (gnat_exit_status); 23736 end; 23737 23738-- This section is entirely comments, so it has no effect on the 23739-- compilation of the Ada_Main package. It provides the list of 23740-- object files and linker options, as well as some standard 23741-- libraries needed for the link. The gnatlink utility parses 23742-- this b~hello.adb file to read these comment lines to generate 23743-- the appropriate command line arguments for the call to the 23744-- system linker. The BEGIN/END lines are used for sentinels for 23745-- this parsing operation. 23746 23747-- The exact file names will of course depend on the environment, 23748-- host/target and location of files on the host system. 23749 23750@findex Object file list 23751-- BEGIN Object file/option list 23752 -- ./hello.o 23753 -- -L./ 23754 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/ 23755 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a 23756-- END Object file/option list 23757 23758end ada_main; 23759@end smallexample 23760 23761@noindent 23762The Ada code in the above example is exactly what is generated by the 23763binder. We have added comments to more clearly indicate the function 23764of each part of the generated @code{Ada_Main} package. 23765 23766The code is standard Ada in all respects, and can be processed by any 23767tools that handle Ada. In particular, it is possible to use the debugger 23768in Ada mode to debug the generated @code{Ada_Main} package. For example, 23769suppose that for reasons that you do not understand, your program is crashing 23770during elaboration of the body of @code{Ada.Text_IO}. To locate this bug, 23771you can place a breakpoint on the call: 23772 23773@smallexample @c ada 23774Ada.Text_Io'Elab_Body; 23775@end smallexample 23776 23777@noindent 23778and trace the elaboration routine for this package to find out where 23779the problem might be (more usually of course you would be debugging 23780elaboration code in your own application). 23781 23782@node Elaboration Order Handling in GNAT 23783@appendix Elaboration Order Handling in GNAT 23784@cindex Order of elaboration 23785@cindex Elaboration control 23786 23787@menu 23788* Elaboration Code:: 23789* Checking the Elaboration Order:: 23790* Controlling the Elaboration Order:: 23791* Controlling Elaboration in GNAT - Internal Calls:: 23792* Controlling Elaboration in GNAT - External Calls:: 23793* Default Behavior in GNAT - Ensuring Safety:: 23794* Treatment of Pragma Elaborate:: 23795* Elaboration Issues for Library Tasks:: 23796* Mixing Elaboration Models:: 23797* What to Do If the Default Elaboration Behavior Fails:: 23798* Elaboration for Dispatching Calls:: 23799* Summary of Procedures for Elaboration Control:: 23800* Other Elaboration Order Considerations:: 23801@end menu 23802 23803@noindent 23804This chapter describes the handling of elaboration code in Ada and 23805in GNAT, and discusses how the order of elaboration of program units can 23806be controlled in GNAT, either automatically or with explicit programming 23807features. 23808 23809@node Elaboration Code 23810@section Elaboration Code 23811 23812@noindent 23813Ada provides rather general mechanisms for executing code at elaboration 23814time, that is to say before the main program starts executing. Such code arises 23815in three contexts: 23816 23817@table @asis 23818@item Initializers for variables. 23819Variables declared at the library level, in package specs or bodies, can 23820require initialization that is performed at elaboration time, as in: 23821@smallexample @c ada 23822@cartouche 23823Sqrt_Half : Float := Sqrt (0.5); 23824@end cartouche 23825@end smallexample 23826 23827@item Package initialization code 23828Code in a @code{BEGIN-END} section at the outer level of a package body is 23829executed as part of the package body elaboration code. 23830 23831@item Library level task allocators 23832Tasks that are declared using task allocators at the library level 23833start executing immediately and hence can execute at elaboration time. 23834@end table 23835 23836@noindent 23837Subprogram calls are possible in any of these contexts, which means that 23838any arbitrary part of the program may be executed as part of the elaboration 23839code. It is even possible to write a program which does all its work at 23840elaboration time, with a null main program, although stylistically this 23841would usually be considered an inappropriate way to structure 23842a program. 23843 23844An important concern arises in the context of elaboration code: 23845we have to be sure that it is executed in an appropriate order. What we 23846have is a series of elaboration code sections, potentially one section 23847for each unit in the program. It is important that these execute 23848in the correct order. Correctness here means that, taking the above 23849example of the declaration of @code{Sqrt_Half}, 23850if some other piece of 23851elaboration code references @code{Sqrt_Half}, 23852then it must run after the 23853section of elaboration code that contains the declaration of 23854@code{Sqrt_Half}. 23855 23856There would never be any order of elaboration problem if we made a rule 23857that whenever you @code{with} a unit, you must elaborate both the spec and body 23858of that unit before elaborating the unit doing the @code{with}'ing: 23859 23860@smallexample @c ada 23861@group 23862@cartouche 23863with Unit_1; 23864package Unit_2 is @dots{} 23865@end cartouche 23866@end group 23867@end smallexample 23868 23869@noindent 23870would require that both the body and spec of @code{Unit_1} be elaborated 23871before the spec of @code{Unit_2}. However, a rule like that would be far too 23872restrictive. In particular, it would make it impossible to have routines 23873in separate packages that were mutually recursive. 23874 23875You might think that a clever enough compiler could look at the actual 23876elaboration code and determine an appropriate correct order of elaboration, 23877but in the general case, this is not possible. Consider the following 23878example. 23879 23880In the body of @code{Unit_1}, we have a procedure @code{Func_1} 23881that references 23882the variable @code{Sqrt_1}, which is declared in the elaboration code 23883of the body of @code{Unit_1}: 23884 23885@smallexample @c ada 23886@cartouche 23887Sqrt_1 : Float := Sqrt (0.1); 23888@end cartouche 23889@end smallexample 23890 23891@noindent 23892The elaboration code of the body of @code{Unit_1} also contains: 23893 23894@smallexample @c ada 23895@group 23896@cartouche 23897if expression_1 = 1 then 23898 Q := Unit_2.Func_2; 23899end if; 23900@end cartouche 23901@end group 23902@end smallexample 23903 23904@noindent 23905@code{Unit_2} is exactly parallel, 23906it has a procedure @code{Func_2} that references 23907the variable @code{Sqrt_2}, which is declared in the elaboration code of 23908the body @code{Unit_2}: 23909 23910@smallexample @c ada 23911@cartouche 23912Sqrt_2 : Float := Sqrt (0.1); 23913@end cartouche 23914@end smallexample 23915 23916@noindent 23917The elaboration code of the body of @code{Unit_2} also contains: 23918 23919@smallexample @c ada 23920@group 23921@cartouche 23922if expression_2 = 2 then 23923 Q := Unit_1.Func_1; 23924end if; 23925@end cartouche 23926@end group 23927@end smallexample 23928 23929@noindent 23930Now the question is, which of the following orders of elaboration is 23931acceptable: 23932 23933@smallexample 23934@group 23935Spec of Unit_1 23936Spec of Unit_2 23937Body of Unit_1 23938Body of Unit_2 23939@end group 23940@end smallexample 23941 23942@noindent 23943or 23944 23945@smallexample 23946@group 23947Spec of Unit_2 23948Spec of Unit_1 23949Body of Unit_2 23950Body of Unit_1 23951@end group 23952@end smallexample 23953 23954@noindent 23955If you carefully analyze the flow here, you will see that you cannot tell 23956at compile time the answer to this question. 23957If @code{expression_1} is not equal to 1, 23958and @code{expression_2} is not equal to 2, 23959then either order is acceptable, because neither of the function calls is 23960executed. If both tests evaluate to true, then neither order is acceptable 23961and in fact there is no correct order. 23962 23963If one of the two expressions is true, and the other is false, then one 23964of the above orders is correct, and the other is incorrect. For example, 23965if @code{expression_1} /= 1 and @code{expression_2} = 2, 23966then the call to @code{Func_1} 23967will occur, but not the call to @code{Func_2.} 23968This means that it is essential 23969to elaborate the body of @code{Unit_1} before 23970the body of @code{Unit_2}, so the first 23971order of elaboration is correct and the second is wrong. 23972 23973By making @code{expression_1} and @code{expression_2} 23974depend on input data, or perhaps 23975the time of day, we can make it impossible for the compiler or binder 23976to figure out which of these expressions will be true, and hence it 23977is impossible to guarantee a safe order of elaboration at run time. 23978 23979@node Checking the Elaboration Order 23980@section Checking the Elaboration Order 23981 23982@noindent 23983In some languages that involve the same kind of elaboration problems, 23984e.g.@: Java and C++, the programmer is expected to worry about these 23985ordering problems himself, and it is common to 23986write a program in which an incorrect elaboration order gives 23987surprising results, because it references variables before they 23988are initialized. 23989Ada is designed to be a safe language, and a programmer-beware approach is 23990clearly not sufficient. Consequently, the language provides three lines 23991of defense: 23992 23993@table @asis 23994@item Standard rules 23995Some standard rules restrict the possible choice of elaboration 23996order. In particular, if you @code{with} a unit, then its spec is always 23997elaborated before the unit doing the @code{with}. Similarly, a parent 23998spec is always elaborated before the child spec, and finally 23999a spec is always elaborated before its corresponding body. 24000 24001@item Dynamic elaboration checks 24002@cindex Elaboration checks 24003@cindex Checks, elaboration 24004Dynamic checks are made at run time, so that if some entity is accessed 24005before it is elaborated (typically by means of a subprogram call) 24006then the exception (@code{Program_Error}) is raised. 24007 24008@item Elaboration control 24009Facilities are provided for the programmer to specify the desired order 24010of elaboration. 24011@end table 24012 24013Let's look at these facilities in more detail. First, the rules for 24014dynamic checking. One possible rule would be simply to say that the 24015exception is raised if you access a variable which has not yet been 24016elaborated. The trouble with this approach is that it could require 24017expensive checks on every variable reference. Instead Ada has two 24018rules which are a little more restrictive, but easier to check, and 24019easier to state: 24020 24021@table @asis 24022@item Restrictions on calls 24023A subprogram can only be called at elaboration time if its body 24024has been elaborated. The rules for elaboration given above guarantee 24025that the spec of the subprogram has been elaborated before the 24026call, but not the body. If this rule is violated, then the 24027exception @code{Program_Error} is raised. 24028 24029@item Restrictions on instantiations 24030A generic unit can only be instantiated if the body of the generic 24031unit has been elaborated. Again, the rules for elaboration given above 24032guarantee that the spec of the generic unit has been elaborated 24033before the instantiation, but not the body. If this rule is 24034violated, then the exception @code{Program_Error} is raised. 24035@end table 24036 24037@noindent 24038The idea is that if the body has been elaborated, then any variables 24039it references must have been elaborated; by checking for the body being 24040elaborated we guarantee that none of its references causes any 24041trouble. As we noted above, this is a little too restrictive, because a 24042subprogram that has no non-local references in its body may in fact be safe 24043to call. However, it really would be unsafe to rely on this, because 24044it would mean that the caller was aware of details of the implementation 24045in the body. This goes against the basic tenets of Ada. 24046 24047A plausible implementation can be described as follows. 24048A Boolean variable is associated with each subprogram 24049and each generic unit. This variable is initialized to False, and is set to 24050True at the point body is elaborated. Every call or instantiation checks the 24051variable, and raises @code{Program_Error} if the variable is False. 24052 24053Note that one might think that it would be good enough to have one Boolean 24054variable for each package, but that would not deal with cases of trying 24055to call a body in the same package as the call 24056that has not been elaborated yet. 24057Of course a compiler may be able to do enough analysis to optimize away 24058some of the Boolean variables as unnecessary, and @code{GNAT} indeed 24059does such optimizations, but still the easiest conceptual model is to 24060think of there being one variable per subprogram. 24061 24062@node Controlling the Elaboration Order 24063@section Controlling the Elaboration Order 24064 24065@noindent 24066In the previous section we discussed the rules in Ada which ensure 24067that @code{Program_Error} is raised if an incorrect elaboration order is 24068chosen. This prevents erroneous executions, but we need mechanisms to 24069specify a correct execution and avoid the exception altogether. 24070To achieve this, Ada provides a number of features for controlling 24071the order of elaboration. We discuss these features in this section. 24072 24073First, there are several ways of indicating to the compiler that a given 24074unit has no elaboration problems: 24075 24076@table @asis 24077@item packages that do not require a body 24078A library package that does not require a body does not permit 24079a body (this rule was introduced in Ada 95). 24080Thus if we have a such a package, as in: 24081 24082@smallexample @c ada 24083@group 24084@cartouche 24085package Definitions is 24086 generic 24087 type m is new integer; 24088 package Subp is 24089 type a is array (1 .. 10) of m; 24090 type b is array (1 .. 20) of m; 24091 end Subp; 24092end Definitions; 24093@end cartouche 24094@end group 24095@end smallexample 24096 24097@noindent 24098A package that @code{with}'s @code{Definitions} may safely instantiate 24099@code{Definitions.Subp} because the compiler can determine that there 24100definitely is no package body to worry about in this case 24101 24102@item pragma Pure 24103@cindex pragma Pure 24104@findex Pure 24105Places sufficient restrictions on a unit to guarantee that 24106no call to any subprogram in the unit can result in an 24107elaboration problem. This means that the compiler does not need 24108to worry about the point of elaboration of such units, and in 24109particular, does not need to check any calls to any subprograms 24110in this unit. 24111 24112@item pragma Preelaborate 24113@findex Preelaborate 24114@cindex pragma Preelaborate 24115This pragma places slightly less stringent restrictions on a unit than 24116does pragma Pure, 24117but these restrictions are still sufficient to ensure that there 24118are no elaboration problems with any calls to the unit. 24119 24120@item pragma Elaborate_Body 24121@findex Elaborate_Body 24122@cindex pragma Elaborate_Body 24123This pragma requires that the body of a unit be elaborated immediately 24124after its spec. Suppose a unit @code{A} has such a pragma, 24125and unit @code{B} does 24126a @code{with} of unit @code{A}. Recall that the standard rules require 24127the spec of unit @code{A} 24128to be elaborated before the @code{with}'ing unit; given the pragma in 24129@code{A}, we also know that the body of @code{A} 24130will be elaborated before @code{B}, so 24131that calls to @code{A} are safe and do not need a check. 24132@end table 24133 24134@noindent 24135Note that, 24136unlike pragma @code{Pure} and pragma @code{Preelaborate}, 24137the use of 24138@code{Elaborate_Body} does not guarantee that the program is 24139free of elaboration problems, because it may not be possible 24140to satisfy the requested elaboration order. 24141Let's go back to the example with @code{Unit_1} and @code{Unit_2}. 24142If a programmer 24143marks @code{Unit_1} as @code{Elaborate_Body}, 24144and not @code{Unit_2,} then the order of 24145elaboration will be: 24146 24147@smallexample 24148@group 24149Spec of Unit_2 24150Spec of Unit_1 24151Body of Unit_1 24152Body of Unit_2 24153@end group 24154@end smallexample 24155 24156@noindent 24157Now that means that the call to @code{Func_1} in @code{Unit_2} 24158need not be checked, 24159it must be safe. But the call to @code{Func_2} in 24160@code{Unit_1} may still fail if 24161@code{Expression_1} is equal to 1, 24162and the programmer must still take 24163responsibility for this not being the case. 24164 24165If all units carry a pragma @code{Elaborate_Body}, then all problems are 24166eliminated, except for calls entirely within a body, which are 24167in any case fully under programmer control. However, using the pragma 24168everywhere is not always possible. 24169In particular, for our @code{Unit_1}/@code{Unit_2} example, if 24170we marked both of them as having pragma @code{Elaborate_Body}, then 24171clearly there would be no possible elaboration order. 24172 24173The above pragmas allow a server to guarantee safe use by clients, and 24174clearly this is the preferable approach. Consequently a good rule 24175is to mark units as @code{Pure} or @code{Preelaborate} if possible, 24176and if this is not possible, 24177mark them as @code{Elaborate_Body} if possible. 24178As we have seen, there are situations where neither of these 24179three pragmas can be used. 24180So we also provide methods for clients to control the 24181order of elaboration of the servers on which they depend: 24182 24183@table @asis 24184@item pragma Elaborate (unit) 24185@findex Elaborate 24186@cindex pragma Elaborate 24187This pragma is placed in the context clause, after a @code{with} clause, 24188and it requires that the body of the named unit be elaborated before 24189the unit in which the pragma occurs. The idea is to use this pragma 24190if the current unit calls at elaboration time, directly or indirectly, 24191some subprogram in the named unit. 24192 24193@item pragma Elaborate_All (unit) 24194@findex Elaborate_All 24195@cindex pragma Elaborate_All 24196This is a stronger version of the Elaborate pragma. Consider the 24197following example: 24198 24199@smallexample 24200Unit A @code{with}'s unit B and calls B.Func in elab code 24201Unit B @code{with}'s unit C, and B.Func calls C.Func 24202@end smallexample 24203 24204@noindent 24205Now if we put a pragma @code{Elaborate (B)} 24206in unit @code{A}, this ensures that the 24207body of @code{B} is elaborated before the call, but not the 24208body of @code{C}, so 24209the call to @code{C.Func} could still cause @code{Program_Error} to 24210be raised. 24211 24212The effect of a pragma @code{Elaborate_All} is stronger, it requires 24213not only that the body of the named unit be elaborated before the 24214unit doing the @code{with}, but also the bodies of all units that the 24215named unit uses, following @code{with} links transitively. For example, 24216if we put a pragma @code{Elaborate_All (B)} in unit @code{A}, 24217then it requires 24218not only that the body of @code{B} be elaborated before @code{A}, 24219but also the 24220body of @code{C}, because @code{B} @code{with}'s @code{C}. 24221@end table 24222 24223@noindent 24224We are now in a position to give a usage rule in Ada for avoiding 24225elaboration problems, at least if dynamic dispatching and access to 24226subprogram values are not used. We will handle these cases separately 24227later. 24228 24229The rule is simple. If a unit has elaboration code that can directly or 24230indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate 24231a generic package in a @code{with}'ed unit, 24232then if the @code{with}'ed unit does not have 24233pragma @code{Pure} or @code{Preelaborate}, then the client should have 24234a pragma @code{Elaborate_All} 24235for the @code{with}'ed unit. By following this rule a client is 24236assured that calls can be made without risk of an exception. 24237 24238For generic subprogram instantiations, the rule can be relaxed to 24239require only a pragma @code{Elaborate} since elaborating the body 24240of a subprogram cannot cause any transitive elaboration (we are 24241not calling the subprogram in this case, just elaborating its 24242declaration). 24243 24244If this rule is not followed, then a program may be in one of four 24245states: 24246 24247@table @asis 24248@item No order exists 24249No order of elaboration exists which follows the rules, taking into 24250account any @code{Elaborate}, @code{Elaborate_All}, 24251or @code{Elaborate_Body} pragmas. In 24252this case, an Ada compiler must diagnose the situation at bind 24253time, and refuse to build an executable program. 24254 24255@item One or more orders exist, all incorrect 24256One or more acceptable elaboration orders exist, and all of them 24257generate an elaboration order problem. In this case, the binder 24258can build an executable program, but @code{Program_Error} will be raised 24259when the program is run. 24260 24261@item Several orders exist, some right, some incorrect 24262One or more acceptable elaboration orders exists, and some of them 24263work, and some do not. The programmer has not controlled 24264the order of elaboration, so the binder may or may not pick one of 24265the correct orders, and the program may or may not raise an 24266exception when it is run. This is the worst case, because it means 24267that the program may fail when moved to another compiler, or even 24268another version of the same compiler. 24269 24270@item One or more orders exists, all correct 24271One ore more acceptable elaboration orders exist, and all of them 24272work. In this case the program runs successfully. This state of 24273affairs can be guaranteed by following the rule we gave above, but 24274may be true even if the rule is not followed. 24275@end table 24276 24277@noindent 24278Note that one additional advantage of following our rules on the use 24279of @code{Elaborate} and @code{Elaborate_All} 24280is that the program continues to stay in the ideal (all orders OK) state 24281even if maintenance 24282changes some bodies of some units. Conversely, if a program that does 24283not follow this rule happens to be safe at some point, this state of affairs 24284may deteriorate silently as a result of maintenance changes. 24285 24286You may have noticed that the above discussion did not mention 24287the use of @code{Elaborate_Body}. This was a deliberate omission. If you 24288@code{with} an @code{Elaborate_Body} unit, it still may be the case that 24289code in the body makes calls to some other unit, so it is still necessary 24290to use @code{Elaborate_All} on such units. 24291 24292@node Controlling Elaboration in GNAT - Internal Calls 24293@section Controlling Elaboration in GNAT - Internal Calls 24294 24295@noindent 24296In the case of internal calls, i.e., calls within a single package, the 24297programmer has full control over the order of elaboration, and it is up 24298to the programmer to elaborate declarations in an appropriate order. For 24299example writing: 24300 24301@smallexample @c ada 24302@group 24303@cartouche 24304function One return Float; 24305 24306Q : Float := One; 24307 24308function One return Float is 24309begin 24310 return 1.0; 24311end One; 24312@end cartouche 24313@end group 24314@end smallexample 24315 24316@noindent 24317will obviously raise @code{Program_Error} at run time, because function 24318One will be called before its body is elaborated. In this case GNAT will 24319generate a warning that the call will raise @code{Program_Error}: 24320 24321@smallexample 24322@group 24323@cartouche 24324 1. procedure y is 24325 2. function One return Float; 24326 3. 24327 4. Q : Float := One; 24328 | 24329 >>> warning: cannot call "One" before body is elaborated 24330 >>> warning: Program_Error will be raised at run time 24331 24332 5. 24333 6. function One return Float is 24334 7. begin 24335 8. return 1.0; 24336 9. end One; 2433710. 2433811. begin 2433912. null; 2434013. end; 24341@end cartouche 24342@end group 24343@end smallexample 24344 24345@noindent 24346Note that in this particular case, it is likely that the call is safe, because 24347the function @code{One} does not access any global variables. 24348Nevertheless in Ada, we do not want the validity of the check to depend on 24349the contents of the body (think about the separate compilation case), so this 24350is still wrong, as we discussed in the previous sections. 24351 24352The error is easily corrected by rearranging the declarations so that the 24353body of @code{One} appears before the declaration containing the call 24354(note that in Ada 95 and Ada 2005, 24355declarations can appear in any order, so there is no restriction that 24356would prevent this reordering, and if we write: 24357 24358@smallexample @c ada 24359@group 24360@cartouche 24361function One return Float; 24362 24363function One return Float is 24364begin 24365 return 1.0; 24366end One; 24367 24368Q : Float := One; 24369@end cartouche 24370@end group 24371@end smallexample 24372 24373@noindent 24374then all is well, no warning is generated, and no 24375@code{Program_Error} exception 24376will be raised. 24377Things are more complicated when a chain of subprograms is executed: 24378 24379@smallexample @c ada 24380@group 24381@cartouche 24382function A return Integer; 24383function B return Integer; 24384function C return Integer; 24385 24386function B return Integer is begin return A; end; 24387function C return Integer is begin return B; end; 24388 24389X : Integer := C; 24390 24391function A return Integer is begin return 1; end; 24392@end cartouche 24393@end group 24394@end smallexample 24395 24396@noindent 24397Now the call to @code{C} 24398at elaboration time in the declaration of @code{X} is correct, because 24399the body of @code{C} is already elaborated, 24400and the call to @code{B} within the body of 24401@code{C} is correct, but the call 24402to @code{A} within the body of @code{B} is incorrect, because the body 24403of @code{A} has not been elaborated, so @code{Program_Error} 24404will be raised on the call to @code{A}. 24405In this case GNAT will generate a 24406warning that @code{Program_Error} may be 24407raised at the point of the call. Let's look at the warning: 24408 24409@smallexample 24410@group 24411@cartouche 24412 1. procedure x is 24413 2. function A return Integer; 24414 3. function B return Integer; 24415 4. function C return Integer; 24416 5. 24417 6. function B return Integer is begin return A; end; 24418 | 24419 >>> warning: call to "A" before body is elaborated may 24420 raise Program_Error 24421 >>> warning: "B" called at line 7 24422 >>> warning: "C" called at line 9 24423 24424 7. function C return Integer is begin return B; end; 24425 8. 24426 9. X : Integer := C; 2442710. 2442811. function A return Integer is begin return 1; end; 2442912. 2443013. begin 2443114. null; 2443215. end; 24433@end cartouche 24434@end group 24435@end smallexample 24436 24437@noindent 24438Note that the message here says ``may raise'', instead of the direct case, 24439where the message says ``will be raised''. That's because whether 24440@code{A} is 24441actually called depends in general on run-time flow of control. 24442For example, if the body of @code{B} said 24443 24444@smallexample @c ada 24445@group 24446@cartouche 24447function B return Integer is 24448begin 24449 if some-condition-depending-on-input-data then 24450 return A; 24451 else 24452 return 1; 24453 end if; 24454end B; 24455@end cartouche 24456@end group 24457@end smallexample 24458 24459@noindent 24460then we could not know until run time whether the incorrect call to A would 24461actually occur, so @code{Program_Error} might 24462or might not be raised. It is possible for a compiler to 24463do a better job of analyzing bodies, to 24464determine whether or not @code{Program_Error} 24465might be raised, but it certainly 24466couldn't do a perfect job (that would require solving the halting problem 24467and is provably impossible), and because this is a warning anyway, it does 24468not seem worth the effort to do the analysis. Cases in which it 24469would be relevant are rare. 24470 24471In practice, warnings of either of the forms given 24472above will usually correspond to 24473real errors, and should be examined carefully and eliminated. 24474In the rare case where a warning is bogus, it can be suppressed by any of 24475the following methods: 24476 24477@itemize @bullet 24478@item 24479Compile with the @option{-gnatws} switch set 24480 24481@item 24482Suppress @code{Elaboration_Check} for the called subprogram 24483 24484@item 24485Use pragma @code{Warnings_Off} to turn warnings off for the call 24486@end itemize 24487 24488@noindent 24489For the internal elaboration check case, 24490GNAT by default generates the 24491necessary run-time checks to ensure 24492that @code{Program_Error} is raised if any 24493call fails an elaboration check. Of course this can only happen if a 24494warning has been issued as described above. The use of pragma 24495@code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress 24496some of these checks, meaning that it may be possible (but is not 24497guaranteed) for a program to be able to call a subprogram whose body 24498is not yet elaborated, without raising a @code{Program_Error} exception. 24499 24500@node Controlling Elaboration in GNAT - External Calls 24501@section Controlling Elaboration in GNAT - External Calls 24502 24503@noindent 24504The previous section discussed the case in which the execution of a 24505particular thread of elaboration code occurred entirely within a 24506single unit. This is the easy case to handle, because a programmer 24507has direct and total control over the order of elaboration, and 24508furthermore, checks need only be generated in cases which are rare 24509and which the compiler can easily detect. 24510The situation is more complex when separate compilation is taken into account. 24511Consider the following: 24512 24513@smallexample @c ada 24514@cartouche 24515@group 24516package Math is 24517 function Sqrt (Arg : Float) return Float; 24518end Math; 24519 24520package body Math is 24521 function Sqrt (Arg : Float) return Float is 24522 begin 24523 @dots{} 24524 end Sqrt; 24525end Math; 24526@end group 24527@group 24528with Math; 24529package Stuff is 24530 X : Float := Math.Sqrt (0.5); 24531end Stuff; 24532 24533with Stuff; 24534procedure Main is 24535begin 24536 @dots{} 24537end Main; 24538@end group 24539@end cartouche 24540@end smallexample 24541 24542@noindent 24543where @code{Main} is the main program. When this program is executed, the 24544elaboration code must first be executed, and one of the jobs of the 24545binder is to determine the order in which the units of a program are 24546to be elaborated. In this case we have four units: the spec and body 24547of @code{Math}, 24548the spec of @code{Stuff} and the body of @code{Main}). 24549In what order should the four separate sections of elaboration code 24550be executed? 24551 24552There are some restrictions in the order of elaboration that the binder 24553can choose. In particular, if unit U has a @code{with} 24554for a package @code{X}, then you 24555are assured that the spec of @code{X} 24556is elaborated before U , but you are 24557not assured that the body of @code{X} 24558is elaborated before U. 24559This means that in the above case, the binder is allowed to choose the 24560order: 24561 24562@smallexample 24563spec of Math 24564spec of Stuff 24565body of Math 24566body of Main 24567@end smallexample 24568 24569@noindent 24570but that's not good, because now the call to @code{Math.Sqrt} 24571that happens during 24572the elaboration of the @code{Stuff} 24573spec happens before the body of @code{Math.Sqrt} is 24574elaborated, and hence causes @code{Program_Error} exception to be raised. 24575At first glance, one might say that the binder is misbehaving, because 24576obviously you want to elaborate the body of something you @code{with} 24577first, but 24578that is not a general rule that can be followed in all cases. Consider 24579 24580@smallexample @c ada 24581@group 24582@cartouche 24583package X is @dots{} 24584 24585package Y is @dots{} 24586 24587with X; 24588package body Y is @dots{} 24589 24590with Y; 24591package body X is @dots{} 24592@end cartouche 24593@end group 24594@end smallexample 24595 24596@noindent 24597This is a common arrangement, and, apart from the order of elaboration 24598problems that might arise in connection with elaboration code, this works fine. 24599A rule that says that you must first elaborate the body of anything you 24600@code{with} cannot work in this case: 24601the body of @code{X} @code{with}'s @code{Y}, 24602which means you would have to 24603elaborate the body of @code{Y} first, but that @code{with}'s @code{X}, 24604which means 24605you have to elaborate the body of @code{X} first, but @dots{} and we have a 24606loop that cannot be broken. 24607 24608It is true that the binder can in many cases guess an order of elaboration 24609that is unlikely to cause a @code{Program_Error} 24610exception to be raised, and it tries to do so (in the 24611above example of @code{Math/Stuff/Spec}, the GNAT binder will 24612by default 24613elaborate the body of @code{Math} right after its spec, so all will be well). 24614 24615However, a program that blindly relies on the binder to be helpful can 24616get into trouble, as we discussed in the previous sections, so 24617GNAT 24618provides a number of facilities for assisting the programmer in 24619developing programs that are robust with respect to elaboration order. 24620 24621@node Default Behavior in GNAT - Ensuring Safety 24622@section Default Behavior in GNAT - Ensuring Safety 24623 24624@noindent 24625The default behavior in GNAT ensures elaboration safety. In its 24626default mode GNAT implements the 24627rule we previously described as the right approach. Let's restate it: 24628 24629@itemize 24630@item 24631@emph{If a unit has elaboration code that can directly or indirectly make a 24632call to a subprogram in a @code{with}'ed unit, or instantiate a generic 24633package in a @code{with}'ed unit, then if the @code{with}'ed unit 24634does not have pragma @code{Pure} or 24635@code{Preelaborate}, then the client should have an 24636@code{Elaborate_All} pragma for the @code{with}'ed unit.} 24637 24638@emph{In the case of instantiating a generic subprogram, it is always 24639sufficient to have only an @code{Elaborate} pragma for the 24640@code{with}'ed unit.} 24641@end itemize 24642 24643@noindent 24644By following this rule a client is assured that calls and instantiations 24645can be made without risk of an exception. 24646 24647In this mode GNAT traces all calls that are potentially made from 24648elaboration code, and puts in any missing implicit @code{Elaborate} 24649and @code{Elaborate_All} pragmas. 24650The advantage of this approach is that no elaboration problems 24651are possible if the binder can find an elaboration order that is 24652consistent with these implicit @code{Elaborate} and 24653@code{Elaborate_All} pragmas. The 24654disadvantage of this approach is that no such order may exist. 24655 24656If the binder does not generate any diagnostics, then it means that it has 24657found an elaboration order that is guaranteed to be safe. However, the binder 24658may still be relying on implicitly generated @code{Elaborate} and 24659@code{Elaborate_All} pragmas so portability to other compilers than GNAT is not 24660guaranteed. 24661 24662If it is important to guarantee portability, then the compilations should 24663use the 24664@option{-gnatwl} 24665(warn on elaboration problems) switch. This will cause warning messages 24666to be generated indicating the missing @code{Elaborate} and 24667@code{Elaborate_All} pragmas. 24668Consider the following source program: 24669 24670@smallexample @c ada 24671@group 24672@cartouche 24673with k; 24674package j is 24675 m : integer := k.r; 24676end; 24677@end cartouche 24678@end group 24679@end smallexample 24680 24681@noindent 24682where it is clear that there 24683should be a pragma @code{Elaborate_All} 24684for unit @code{k}. An implicit pragma will be generated, and it is 24685likely that the binder will be able to honor it. However, if you want 24686to port this program to some other Ada compiler than GNAT. 24687it is safer to include the pragma explicitly in the source. If this 24688unit is compiled with the 24689@option{-gnatwl} 24690switch, then the compiler outputs a warning: 24691 24692@smallexample 24693@group 24694@cartouche 246951. with k; 246962. package j is 246973. m : integer := k.r; 24698 | 24699 >>> warning: call to "r" may raise Program_Error 24700 >>> warning: missing pragma Elaborate_All for "k" 24701 247024. end; 24703@end cartouche 24704@end group 24705@end smallexample 24706 24707@noindent 24708and these warnings can be used as a guide for supplying manually 24709the missing pragmas. It is usually a bad idea to use this warning 24710option during development. That's because it will warn you when 24711you need to put in a pragma, but cannot warn you when it is time 24712to take it out. So the use of pragma @code{Elaborate_All} may lead to 24713unnecessary dependencies and even false circularities. 24714 24715This default mode is more restrictive than the Ada Reference 24716Manual, and it is possible to construct programs which will compile 24717using the dynamic model described there, but will run into a 24718circularity using the safer static model we have described. 24719 24720Of course any Ada compiler must be able to operate in a mode 24721consistent with the requirements of the Ada Reference Manual, 24722and in particular must have the capability of implementing the 24723standard dynamic model of elaboration with run-time checks. 24724 24725In GNAT, this standard mode can be achieved either by the use of 24726the @option{-gnatE} switch on the compiler (@command{gcc} or 24727@command{gnatmake}) command, or by the use of the configuration pragma: 24728 24729@smallexample @c ada 24730pragma Elaboration_Checks (DYNAMIC); 24731@end smallexample 24732 24733@noindent 24734Either approach will cause the unit affected to be compiled using the 24735standard dynamic run-time elaboration checks described in the Ada 24736Reference Manual. The static model is generally preferable, since it 24737is clearly safer to rely on compile and link time checks rather than 24738run-time checks. However, in the case of legacy code, it may be 24739difficult to meet the requirements of the static model. This 24740issue is further discussed in 24741@ref{What to Do If the Default Elaboration Behavior Fails}. 24742 24743Note that the static model provides a strict subset of the allowed 24744behavior and programs of the Ada Reference Manual, so if you do 24745adhere to the static model and no circularities exist, 24746then you are assured that your program will 24747work using the dynamic model, providing that you remove any 24748pragma Elaborate statements from the source. 24749 24750@node Treatment of Pragma Elaborate 24751@section Treatment of Pragma Elaborate 24752@cindex Pragma Elaborate 24753 24754@noindent 24755The use of @code{pragma Elaborate} 24756should generally be avoided in Ada 95 and Ada 2005 programs, 24757since there is no guarantee that transitive calls 24758will be properly handled. Indeed at one point, this pragma was placed 24759in Annex J (Obsolescent Features), on the grounds that it is never useful. 24760 24761Now that's a bit restrictive. In practice, the case in which 24762@code{pragma Elaborate} is useful is when the caller knows that there 24763are no transitive calls, or that the called unit contains all necessary 24764transitive @code{pragma Elaborate} statements, and legacy code often 24765contains such uses. 24766 24767Strictly speaking the static mode in GNAT should ignore such pragmas, 24768since there is no assurance at compile time that the necessary safety 24769conditions are met. In practice, this would cause GNAT to be incompatible 24770with correctly written Ada 83 code that had all necessary 24771@code{pragma Elaborate} statements in place. Consequently, we made the 24772decision that GNAT in its default mode will believe that if it encounters 24773a @code{pragma Elaborate} then the programmer knows what they are doing, 24774and it will trust that no elaboration errors can occur. 24775 24776The result of this decision is two-fold. First to be safe using the 24777static mode, you should remove all @code{pragma Elaborate} statements. 24778Second, when fixing circularities in existing code, you can selectively 24779use @code{pragma Elaborate} statements to convince the static mode of 24780GNAT that it need not generate an implicit @code{pragma Elaborate_All} 24781statement. 24782 24783When using the static mode with @option{-gnatwl}, any use of 24784@code{pragma Elaborate} will generate a warning about possible 24785problems. 24786 24787@node Elaboration Issues for Library Tasks 24788@section Elaboration Issues for Library Tasks 24789@cindex Library tasks, elaboration issues 24790@cindex Elaboration of library tasks 24791 24792@noindent 24793In this section we examine special elaboration issues that arise for 24794programs that declare library level tasks. 24795 24796Generally the model of execution of an Ada program is that all units are 24797elaborated, and then execution of the program starts. However, the 24798declaration of library tasks definitely does not fit this model. The 24799reason for this is that library tasks start as soon as they are declared 24800(more precisely, as soon as the statement part of the enclosing package 24801body is reached), that is to say before elaboration 24802of the program is complete. This means that if such a task calls a 24803subprogram, or an entry in another task, the callee may or may not be 24804elaborated yet, and in the standard 24805Reference Manual model of dynamic elaboration checks, you can even 24806get timing dependent Program_Error exceptions, since there can be 24807a race between the elaboration code and the task code. 24808 24809The static model of elaboration in GNAT seeks to avoid all such 24810dynamic behavior, by being conservative, and the conservative 24811approach in this particular case is to assume that all the code 24812in a task body is potentially executed at elaboration time if 24813a task is declared at the library level. 24814 24815This can definitely result in unexpected circularities. Consider 24816the following example 24817 24818@smallexample @c ada 24819package Decls is 24820 task Lib_Task is 24821 entry Start; 24822 end Lib_Task; 24823 24824 type My_Int is new Integer; 24825 24826 function Ident (M : My_Int) return My_Int; 24827end Decls; 24828 24829with Utils; 24830package body Decls is 24831 task body Lib_Task is 24832 begin 24833 accept Start; 24834 Utils.Put_Val (2); 24835 end Lib_Task; 24836 24837 function Ident (M : My_Int) return My_Int is 24838 begin 24839 return M; 24840 end Ident; 24841end Decls; 24842 24843with Decls; 24844package Utils is 24845 procedure Put_Val (Arg : Decls.My_Int); 24846end Utils; 24847 24848with Text_IO; 24849package body Utils is 24850 procedure Put_Val (Arg : Decls.My_Int) is 24851 begin 24852 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); 24853 end Put_Val; 24854end Utils; 24855 24856with Decls; 24857procedure Main is 24858begin 24859 Decls.Lib_Task.Start; 24860end; 24861@end smallexample 24862 24863@noindent 24864If the above example is compiled in the default static elaboration 24865mode, then a circularity occurs. The circularity comes from the call 24866@code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since 24867this call occurs in elaboration code, we need an implicit pragma 24868@code{Elaborate_All} for @code{Utils}. This means that not only must 24869the spec and body of @code{Utils} be elaborated before the body 24870of @code{Decls}, but also the spec and body of any unit that is 24871@code{with'ed} by the body of @code{Utils} must also be elaborated before 24872the body of @code{Decls}. This is the transitive implication of 24873pragma @code{Elaborate_All} and it makes sense, because in general 24874the body of @code{Put_Val} might have a call to something in a 24875@code{with'ed} unit. 24876 24877In this case, the body of Utils (actually its spec) @code{with's} 24878@code{Decls}. Unfortunately this means that the body of @code{Decls} 24879must be elaborated before itself, in case there is a call from the 24880body of @code{Utils}. 24881 24882Here is the exact chain of events we are worrying about: 24883 24884@enumerate 24885@item 24886In the body of @code{Decls} a call is made from within the body of a library 24887task to a subprogram in the package @code{Utils}. Since this call may 24888occur at elaboration time (given that the task is activated at elaboration 24889time), we have to assume the worst, i.e., that the 24890call does happen at elaboration time. 24891 24892@item 24893This means that the body and spec of @code{Util} must be elaborated before 24894the body of @code{Decls} so that this call does not cause an access before 24895elaboration. 24896 24897@item 24898Within the body of @code{Util}, specifically within the body of 24899@code{Util.Put_Val} there may be calls to any unit @code{with}'ed 24900by this package. 24901 24902@item 24903One such @code{with}'ed package is package @code{Decls}, so there 24904might be a call to a subprogram in @code{Decls} in @code{Put_Val}. 24905In fact there is such a call in this example, but we would have to 24906assume that there was such a call even if it were not there, since 24907we are not supposed to write the body of @code{Decls} knowing what 24908is in the body of @code{Utils}; certainly in the case of the 24909static elaboration model, the compiler does not know what is in 24910other bodies and must assume the worst. 24911 24912@item 24913This means that the spec and body of @code{Decls} must also be 24914elaborated before we elaborate the unit containing the call, but 24915that unit is @code{Decls}! This means that the body of @code{Decls} 24916must be elaborated before itself, and that's a circularity. 24917@end enumerate 24918 24919@noindent 24920Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in 24921the body of @code{Decls} you will get a true Ada Reference Manual 24922circularity that makes the program illegal. 24923 24924In practice, we have found that problems with the static model of 24925elaboration in existing code often arise from library tasks, so 24926we must address this particular situation. 24927 24928Note that if we compile and run the program above, using the dynamic model of 24929elaboration (that is to say use the @option{-gnatE} switch), 24930then it compiles, binds, 24931links, and runs, printing the expected result of 2. Therefore in some sense 24932the circularity here is only apparent, and we need to capture 24933the properties of this program that distinguish it from other library-level 24934tasks that have real elaboration problems. 24935 24936We have four possible answers to this question: 24937 24938@itemize @bullet 24939 24940@item 24941Use the dynamic model of elaboration. 24942 24943If we use the @option{-gnatE} switch, then as noted above, the program works. 24944Why is this? If we examine the task body, it is apparent that the task cannot 24945proceed past the 24946@code{accept} statement until after elaboration has been completed, because 24947the corresponding entry call comes from the main program, not earlier. 24948This is why the dynamic model works here. But that's really giving 24949up on a precise analysis, and we prefer to take this approach only if we cannot 24950solve the 24951problem in any other manner. So let us examine two ways to reorganize 24952the program to avoid the potential elaboration problem. 24953 24954@item 24955Split library tasks into separate packages. 24956 24957Write separate packages, so that library tasks are isolated from 24958other declarations as much as possible. Let us look at a variation on 24959the above program. 24960 24961@smallexample @c ada 24962package Decls1 is 24963 task Lib_Task is 24964 entry Start; 24965 end Lib_Task; 24966end Decls1; 24967 24968with Utils; 24969package body Decls1 is 24970 task body Lib_Task is 24971 begin 24972 accept Start; 24973 Utils.Put_Val (2); 24974 end Lib_Task; 24975end Decls1; 24976 24977package Decls2 is 24978 type My_Int is new Integer; 24979 function Ident (M : My_Int) return My_Int; 24980end Decls2; 24981 24982with Utils; 24983package body Decls2 is 24984 function Ident (M : My_Int) return My_Int is 24985 begin 24986 return M; 24987 end Ident; 24988end Decls2; 24989 24990with Decls2; 24991package Utils is 24992 procedure Put_Val (Arg : Decls2.My_Int); 24993end Utils; 24994 24995with Text_IO; 24996package body Utils is 24997 procedure Put_Val (Arg : Decls2.My_Int) is 24998 begin 24999 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg))); 25000 end Put_Val; 25001end Utils; 25002 25003with Decls1; 25004procedure Main is 25005begin 25006 Decls1.Lib_Task.Start; 25007end; 25008@end smallexample 25009 25010@noindent 25011All we have done is to split @code{Decls} into two packages, one 25012containing the library task, and one containing everything else. Now 25013there is no cycle, and the program compiles, binds, links and executes 25014using the default static model of elaboration. 25015 25016@item 25017Declare separate task types. 25018 25019A significant part of the problem arises because of the use of the 25020single task declaration form. This means that the elaboration of 25021the task type, and the elaboration of the task itself (i.e.@: the 25022creation of the task) happen at the same time. A good rule 25023of style in Ada is to always create explicit task types. By 25024following the additional step of placing task objects in separate 25025packages from the task type declaration, many elaboration problems 25026are avoided. Here is another modified example of the example program: 25027 25028@smallexample @c ada 25029package Decls is 25030 task type Lib_Task_Type is 25031 entry Start; 25032 end Lib_Task_Type; 25033 25034 type My_Int is new Integer; 25035 25036 function Ident (M : My_Int) return My_Int; 25037end Decls; 25038 25039with Utils; 25040package body Decls is 25041 task body Lib_Task_Type is 25042 begin 25043 accept Start; 25044 Utils.Put_Val (2); 25045 end Lib_Task_Type; 25046 25047 function Ident (M : My_Int) return My_Int is 25048 begin 25049 return M; 25050 end Ident; 25051end Decls; 25052 25053with Decls; 25054package Utils is 25055 procedure Put_Val (Arg : Decls.My_Int); 25056end Utils; 25057 25058with Text_IO; 25059package body Utils is 25060 procedure Put_Val (Arg : Decls.My_Int) is 25061 begin 25062 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg))); 25063 end Put_Val; 25064end Utils; 25065 25066with Decls; 25067package Declst is 25068 Lib_Task : Decls.Lib_Task_Type; 25069end Declst; 25070 25071with Declst; 25072procedure Main is 25073begin 25074 Declst.Lib_Task.Start; 25075end; 25076@end smallexample 25077 25078@noindent 25079What we have done here is to replace the @code{task} declaration in 25080package @code{Decls} with a @code{task type} declaration. Then we 25081introduce a separate package @code{Declst} to contain the actual 25082task object. This separates the elaboration issues for 25083the @code{task type} 25084declaration, which causes no trouble, from the elaboration issues 25085of the task object, which is also unproblematic, since it is now independent 25086of the elaboration of @code{Utils}. 25087This separation of concerns also corresponds to 25088a generally sound engineering principle of separating declarations 25089from instances. This version of the program also compiles, binds, links, 25090and executes, generating the expected output. 25091 25092@item 25093Use No_Entry_Calls_In_Elaboration_Code restriction. 25094@cindex No_Entry_Calls_In_Elaboration_Code 25095 25096The previous two approaches described how a program can be restructured 25097to avoid the special problems caused by library task bodies. in practice, 25098however, such restructuring may be difficult to apply to existing legacy code, 25099so we must consider solutions that do not require massive rewriting. 25100 25101Let us consider more carefully why our original sample program works 25102under the dynamic model of elaboration. The reason is that the code 25103in the task body blocks immediately on the @code{accept} 25104statement. Now of course there is nothing to prohibit elaboration 25105code from making entry calls (for example from another library level task), 25106so we cannot tell in isolation that 25107the task will not execute the accept statement during elaboration. 25108 25109However, in practice it is very unusual to see elaboration code 25110make any entry calls, and the pattern of tasks starting 25111at elaboration time and then immediately blocking on @code{accept} or 25112@code{select} statements is very common. What this means is that 25113the compiler is being too pessimistic when it analyzes the 25114whole package body as though it might be executed at elaboration 25115time. 25116 25117If we know that the elaboration code contains no entry calls, (a very safe 25118assumption most of the time, that could almost be made the default 25119behavior), then we can compile all units of the program under control 25120of the following configuration pragma: 25121 25122@smallexample 25123pragma Restrictions (No_Entry_Calls_In_Elaboration_Code); 25124@end smallexample 25125 25126@noindent 25127This pragma can be placed in the @file{gnat.adc} file in the usual 25128manner. If we take our original unmodified program and compile it 25129in the presence of a @file{gnat.adc} containing the above pragma, 25130then once again, we can compile, bind, link, and execute, obtaining 25131the expected result. In the presence of this pragma, the compiler does 25132not trace calls in a task body, that appear after the first @code{accept} 25133or @code{select} statement, and therefore does not report a potential 25134circularity in the original program. 25135 25136The compiler will check to the extent it can that the above 25137restriction is not violated, but it is not always possible to do a 25138complete check at compile time, so it is important to use this 25139pragma only if the stated restriction is in fact met, that is to say 25140no task receives an entry call before elaboration of all units is completed. 25141 25142@end itemize 25143 25144@node Mixing Elaboration Models 25145@section Mixing Elaboration Models 25146@noindent 25147So far, we have assumed that the entire program is either compiled 25148using the dynamic model or static model, ensuring consistency. It 25149is possible to mix the two models, but rules have to be followed 25150if this mixing is done to ensure that elaboration checks are not 25151omitted. 25152 25153The basic rule is that @emph{a unit compiled with the static model cannot 25154be @code{with'ed} by a unit compiled with the dynamic model}. The 25155reason for this is that in the static model, a unit assumes that 25156its clients guarantee to use (the equivalent of) pragma 25157@code{Elaborate_All} so that no elaboration checks are required 25158in inner subprograms, and this assumption is violated if the 25159client is compiled with dynamic checks. 25160 25161The precise rule is as follows. A unit that is compiled with dynamic 25162checks can only @code{with} a unit that meets at least one of the 25163following criteria: 25164 25165@itemize @bullet 25166 25167@item 25168The @code{with'ed} unit is itself compiled with dynamic elaboration 25169checks (that is with the @option{-gnatE} switch. 25170 25171@item 25172The @code{with'ed} unit is an internal GNAT implementation unit from 25173the System, Interfaces, Ada, or GNAT hierarchies. 25174 25175@item 25176The @code{with'ed} unit has pragma Preelaborate or pragma Pure. 25177 25178@item 25179The @code{with'ing} unit (that is the client) has an explicit pragma 25180@code{Elaborate_All} for the @code{with'ed} unit. 25181 25182@end itemize 25183 25184@noindent 25185If this rule is violated, that is if a unit with dynamic elaboration 25186checks @code{with's} a unit that does not meet one of the above four 25187criteria, then the binder (@code{gnatbind}) will issue a warning 25188similar to that in the following example: 25189 25190@smallexample 25191warning: "x.ads" has dynamic elaboration checks and with's 25192warning: "y.ads" which has static elaboration checks 25193@end smallexample 25194 25195@noindent 25196These warnings indicate that the rule has been violated, and that as a result 25197elaboration checks may be missed in the resulting executable file. 25198This warning may be suppressed using the @option{-ws} binder switch 25199in the usual manner. 25200 25201One useful application of this mixing rule is in the case of a subsystem 25202which does not itself @code{with} units from the remainder of the 25203application. In this case, the entire subsystem can be compiled with 25204dynamic checks to resolve a circularity in the subsystem, while 25205allowing the main application that uses this subsystem to be compiled 25206using the more reliable default static model. 25207 25208@node What to Do If the Default Elaboration Behavior Fails 25209@section What to Do If the Default Elaboration Behavior Fails 25210 25211@noindent 25212If the binder cannot find an acceptable order, it outputs detailed 25213diagnostics. For example: 25214@smallexample 25215@group 25216@iftex 25217@leftskip=0cm 25218@end iftex 25219error: elaboration circularity detected 25220info: "proc (body)" must be elaborated before "pack (body)" 25221info: reason: Elaborate_All probably needed in unit "pack (body)" 25222info: recompile "pack (body)" with -gnatwl 25223info: for full details 25224info: "proc (body)" 25225info: is needed by its spec: 25226info: "proc (spec)" 25227info: which is withed by: 25228info: "pack (body)" 25229info: "pack (body)" must be elaborated before "proc (body)" 25230info: reason: pragma Elaborate in unit "proc (body)" 25231@end group 25232 25233@end smallexample 25234 25235@noindent 25236In this case we have a cycle that the binder cannot break. On the one 25237hand, there is an explicit pragma Elaborate in @code{proc} for 25238@code{pack}. This means that the body of @code{pack} must be elaborated 25239before the body of @code{proc}. On the other hand, there is elaboration 25240code in @code{pack} that calls a subprogram in @code{proc}. This means 25241that for maximum safety, there should really be a pragma 25242Elaborate_All in @code{pack} for @code{proc} which would require that 25243the body of @code{proc} be elaborated before the body of 25244@code{pack}. Clearly both requirements cannot be satisfied. 25245Faced with a circularity of this kind, you have three different options. 25246 25247@table @asis 25248@item Fix the program 25249The most desirable option from the point of view of long-term maintenance 25250is to rearrange the program so that the elaboration problems are avoided. 25251One useful technique is to place the elaboration code into separate 25252child packages. Another is to move some of the initialization code to 25253explicitly called subprograms, where the program controls the order 25254of initialization explicitly. Although this is the most desirable option, 25255it may be impractical and involve too much modification, especially in 25256the case of complex legacy code. 25257 25258@item Perform dynamic checks 25259If the compilations are done using the 25260@option{-gnatE} 25261(dynamic elaboration check) switch, then GNAT behaves in a quite different 25262manner. Dynamic checks are generated for all calls that could possibly result 25263in raising an exception. With this switch, the compiler does not generate 25264implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is 25265exactly as specified in the @cite{Ada Reference Manual}. 25266The binder will generate 25267an executable program that may or may not raise @code{Program_Error}, and then 25268it is the programmer's job to ensure that it does not raise an exception. Note 25269that it is important to compile all units with the switch, it cannot be used 25270selectively. 25271 25272@item Suppress checks 25273The drawback of dynamic checks is that they generate a 25274significant overhead at run time, both in space and time. If you 25275are absolutely sure that your program cannot raise any elaboration 25276exceptions, and you still want to use the dynamic elaboration model, 25277then you can use the configuration pragma 25278@code{Suppress (Elaboration_Check)} to suppress all such checks. For 25279example this pragma could be placed in the @file{gnat.adc} file. 25280 25281@item Suppress checks selectively 25282When you know that certain calls or instantiations in elaboration code cannot 25283possibly lead to an elaboration error, and the binder nevertheless complains 25284about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to 25285elaboration circularities, it is possible to remove those warnings locally and 25286obtain a program that will bind. Clearly this can be unsafe, and it is the 25287responsibility of the programmer to make sure that the resulting program has no 25288elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be 25289used with different granularity to suppress warnings and break elaboration 25290circularities: 25291 25292@itemize @bullet 25293@item 25294Place the pragma that names the called subprogram in the declarative part 25295that contains the call. 25296 25297@item 25298Place the pragma in the declarative part, without naming an entity. This 25299disables warnings on all calls in the corresponding declarative region. 25300 25301@item 25302Place the pragma in the package spec that declares the called subprogram, 25303and name the subprogram. This disables warnings on all elaboration calls to 25304that subprogram. 25305 25306@item 25307Place the pragma in the package spec that declares the called subprogram, 25308without naming any entity. This disables warnings on all elaboration calls to 25309all subprograms declared in this spec. 25310 25311@item Use Pragma Elaborate 25312As previously described in section @xref{Treatment of Pragma Elaborate}, 25313GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly 25314that no elaboration checks are required on calls to the designated unit. 25315There may be cases in which the caller knows that no transitive calls 25316can occur, so that a @code{pragma Elaborate} will be sufficient in a 25317case where @code{pragma Elaborate_All} would cause a circularity. 25318@end itemize 25319 25320@noindent 25321These five cases are listed in order of decreasing safety, and therefore 25322require increasing programmer care in their application. Consider the 25323following program: 25324 25325@smallexample @c adanocomment 25326package Pack1 is 25327 function F1 return Integer; 25328 X1 : Integer; 25329end Pack1; 25330 25331package Pack2 is 25332 function F2 return Integer; 25333 function Pure (x : integer) return integer; 25334 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3) 25335 -- pragma Suppress (Elaboration_Check); -- (4) 25336end Pack2; 25337 25338with Pack2; 25339package body Pack1 is 25340 function F1 return Integer is 25341 begin 25342 return 100; 25343 end F1; 25344 Val : integer := Pack2.Pure (11); -- Elab. call (1) 25345begin 25346 declare 25347 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1) 25348 -- pragma Suppress(Elaboration_Check); -- (2) 25349 begin 25350 X1 := Pack2.F2 + 1; -- Elab. call (2) 25351 end; 25352end Pack1; 25353 25354with Pack1; 25355package body Pack2 is 25356 function F2 return Integer is 25357 begin 25358 return Pack1.F1; 25359 end F2; 25360 function Pure (x : integer) return integer is 25361 begin 25362 return x ** 3 - 3 * x; 25363 end; 25364end Pack2; 25365 25366with Pack1, Ada.Text_IO; 25367procedure Proc3 is 25368begin 25369 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101 25370end Proc3; 25371@end smallexample 25372In the absence of any pragmas, an attempt to bind this program produces 25373the following diagnostics: 25374@smallexample 25375@group 25376@iftex 25377@leftskip=.5cm 25378@end iftex 25379error: elaboration circularity detected 25380info: "pack1 (body)" must be elaborated before "pack1 (body)" 25381info: reason: Elaborate_All probably needed in unit "pack1 (body)" 25382info: recompile "pack1 (body)" with -gnatwl for full details 25383info: "pack1 (body)" 25384info: must be elaborated along with its spec: 25385info: "pack1 (spec)" 25386info: which is withed by: 25387info: "pack2 (body)" 25388info: which must be elaborated along with its spec: 25389info: "pack2 (spec)" 25390info: which is withed by: 25391info: "pack1 (body)" 25392@end group 25393@end smallexample 25394The sources of the circularity are the two calls to @code{Pack2.Pure} and 25395@code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to 25396F2 is safe, even though F2 calls F1, because the call appears after the 25397elaboration of the body of F1. Therefore the pragma (1) is safe, and will 25398remove the warning on the call. It is also possible to use pragma (2) 25399because there are no other potentially unsafe calls in the block. 25400 25401@noindent 25402The call to @code{Pure} is safe because this function does not depend on the 25403state of @code{Pack2}. Therefore any call to this function is safe, and it 25404is correct to place pragma (3) in the corresponding package spec. 25405 25406@noindent 25407Finally, we could place pragma (4) in the spec of @code{Pack2} to disable 25408warnings on all calls to functions declared therein. Note that this is not 25409necessarily safe, and requires more detailed examination of the subprogram 25410bodies involved. In particular, a call to @code{F2} requires that @code{F1} 25411be already elaborated. 25412@end table 25413 25414@noindent 25415It is hard to generalize on which of these four approaches should be 25416taken. Obviously if it is possible to fix the program so that the default 25417treatment works, this is preferable, but this may not always be practical. 25418It is certainly simple enough to use 25419@option{-gnatE} 25420but the danger in this case is that, even if the GNAT binder 25421finds a correct elaboration order, it may not always do so, 25422and certainly a binder from another Ada compiler might not. A 25423combination of testing and analysis (for which the warnings generated 25424with the 25425@option{-gnatwl} 25426switch can be useful) must be used to ensure that the program is free 25427of errors. One switch that is useful in this testing is the 25428@option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^} 25429switch for 25430@code{gnatbind}. 25431Normally the binder tries to find an order that has the best chance 25432of avoiding elaboration problems. However, if this switch is used, the binder 25433plays a devil's advocate role, and tries to choose the order that 25434has the best chance of failing. If your program works even with this 25435switch, then it has a better chance of being error free, but this is still 25436not a guarantee. 25437 25438For an example of this approach in action, consider the C-tests (executable 25439tests) from the ACVC suite. If these are compiled and run with the default 25440treatment, then all but one of them succeed without generating any error 25441diagnostics from the binder. However, there is one test that fails, and 25442this is not surprising, because the whole point of this test is to ensure 25443that the compiler can handle cases where it is impossible to determine 25444a correct order statically, and it checks that an exception is indeed 25445raised at run time. 25446 25447This one test must be compiled and run using the 25448@option{-gnatE} 25449switch, and then it passes. Alternatively, the entire suite can 25450be run using this switch. It is never wrong to run with the dynamic 25451elaboration switch if your code is correct, and we assume that the 25452C-tests are indeed correct (it is less efficient, but efficiency is 25453not a factor in running the ACVC tests.) 25454 25455@node Elaboration for Dispatching Calls 25456@section Elaboration for Dispatching Calls 25457@cindex Dispatching calls 25458 25459@noindent 25460In rare cases, the static elaboration model fails to prevent 25461dispatching calls to not-yet-elaborated subprograms. In such cases, we 25462fall back to run-time checks; premature calls to any primitive 25463operation of a tagged type before the body of the operation has been 25464elaborated will raise @code{Program_Error}. 25465 25466Access-to-subprogram types, however, are handled conservatively, and 25467do not require run-time checks. This was not true in earlier versions 25468of the compiler; you can use the @option{-gnatd.U} debug switch to 25469revert to the old behavior if the new conservative behavior causes 25470elaboration cycles. 25471 25472@node Summary of Procedures for Elaboration Control 25473@section Summary of Procedures for Elaboration Control 25474@cindex Elaboration control 25475 25476@noindent 25477First, compile your program with the default options, using none of 25478the special elaboration control switches. If the binder successfully 25479binds your program, then you can be confident that, apart from issues 25480raised by the use of access-to-subprogram types and dynamic dispatching, 25481the program is free of elaboration errors. If it is important that the 25482program be portable, then use the 25483@option{-gnatwl} 25484switch to generate warnings about missing @code{Elaborate} or 25485@code{Elaborate_All} pragmas, and supply the missing pragmas. 25486 25487If the program fails to bind using the default static elaboration 25488handling, then you can fix the program to eliminate the binder 25489message, or recompile the entire program with the 25490@option{-gnatE} switch to generate dynamic elaboration checks, 25491and, if you are sure there really are no elaboration problems, 25492use a global pragma @code{Suppress (Elaboration_Check)}. 25493 25494@node Other Elaboration Order Considerations 25495@section Other Elaboration Order Considerations 25496@noindent 25497This section has been entirely concerned with the issue of finding a valid 25498elaboration order, as defined by the Ada Reference Manual. In a case 25499where several elaboration orders are valid, the task is to find one 25500of the possible valid elaboration orders (and the static model in GNAT 25501will ensure that this is achieved). 25502 25503The purpose of the elaboration rules in the Ada Reference Manual is to 25504make sure that no entity is accessed before it has been elaborated. For 25505a subprogram, this means that the spec and body must have been elaborated 25506before the subprogram is called. For an object, this means that the object 25507must have been elaborated before its value is read or written. A violation 25508of either of these two requirements is an access before elaboration order, 25509and this section has been all about avoiding such errors. 25510 25511In the case where more than one order of elaboration is possible, in the 25512sense that access before elaboration errors are avoided, then any one of 25513the orders is ``correct'' in the sense that it meets the requirements of 25514the Ada Reference Manual, and no such error occurs. 25515 25516However, it may be the case for a given program, that there are 25517constraints on the order of elaboration that come not from consideration 25518of avoiding elaboration errors, but rather from extra-lingual logic 25519requirements. Consider this example: 25520 25521@smallexample @c ada 25522with Init_Constants; 25523package Constants is 25524 X : Integer := 0; 25525 Y : Integer := 0; 25526end Constants; 25527 25528package Init_Constants is 25529 procedure P; -- require a body 25530end Init_Constants; 25531 25532with Constants; 25533package body Init_Constants is 25534 procedure P is begin null; end; 25535begin 25536 Constants.X := 3; 25537 Constants.Y := 4; 25538end Init_Constants; 25539 25540with Constants; 25541package Calc is 25542 Z : Integer := Constants.X + Constants.Y; 25543end Calc; 25544 25545with Calc; 25546with Text_IO; use Text_IO; 25547procedure Main is 25548begin 25549 Put_Line (Calc.Z'Img); 25550end Main; 25551@end smallexample 25552 25553@noindent 25554In this example, there is more than one valid order of elaboration. For 25555example both the following are correct orders: 25556 25557@smallexample 25558Init_Constants spec 25559Constants spec 25560Calc spec 25561Init_Constants body 25562Main body 25563 25564 and 25565 25566Init_Constants spec 25567Init_Constants body 25568Constants spec 25569Calc spec 25570Main body 25571@end smallexample 25572 25573@noindent 25574There is no language rule to prefer one or the other, both are correct 25575from an order of elaboration point of view. But the programmatic effects 25576of the two orders are very different. In the first, the elaboration routine 25577of @code{Calc} initializes @code{Z} to zero, and then the main program 25578runs with this value of zero. But in the second order, the elaboration 25579routine of @code{Calc} runs after the body of Init_Constants has set 25580@code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main} 25581runs. 25582 25583One could perhaps by applying pretty clever non-artificial intelligence 25584to the situation guess that it is more likely that the second order of 25585elaboration is the one desired, but there is no formal linguistic reason 25586to prefer one over the other. In fact in this particular case, GNAT will 25587prefer the second order, because of the rule that bodies are elaborated 25588as soon as possible, but it's just luck that this is what was wanted 25589(if indeed the second order was preferred). 25590 25591If the program cares about the order of elaboration routines in a case like 25592this, it is important to specify the order required. In this particular 25593case, that could have been achieved by adding to the spec of Calc: 25594 25595@smallexample @c ada 25596pragma Elaborate_All (Constants); 25597@end smallexample 25598 25599@noindent 25600which requires that the body (if any) and spec of @code{Constants}, 25601as well as the body and spec of any unit @code{with}'ed by 25602@code{Constants} be elaborated before @code{Calc} is elaborated. 25603 25604Clearly no automatic method can always guess which alternative you require, 25605and if you are working with legacy code that had constraints of this kind 25606which were not properly specified by adding @code{Elaborate} or 25607@code{Elaborate_All} pragmas, then indeed it is possible that two different 25608compilers can choose different orders. 25609 25610However, GNAT does attempt to diagnose the common situation where there 25611are uninitialized variables in the visible part of a package spec, and the 25612corresponding package body has an elaboration block that directly or 25613indirectly initialized one or more of these variables. This is the situation 25614in which a pragma Elaborate_Body is usually desirable, and GNAT will generate 25615a warning that suggests this addition if it detects this situation. 25616 25617The @code{gnatbind} 25618@option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking 25619out problems. This switch causes bodies to be elaborated as late as possible 25620instead of as early as possible. In the example above, it would have forced 25621the choice of the first elaboration order. If you get different results 25622when using this switch, and particularly if one set of results is right, 25623and one is wrong as far as you are concerned, it shows that you have some 25624missing @code{Elaborate} pragmas. For the example above, we have the 25625following output: 25626 25627@smallexample 25628gnatmake -f -q main 25629main 25630 7 25631gnatmake -f -q main -bargs -p 25632main 25633 0 25634@end smallexample 25635 25636@noindent 25637It is of course quite unlikely that both these results are correct, so 25638it is up to you in a case like this to investigate the source of the 25639difference, by looking at the two elaboration orders that are chosen, 25640and figuring out which is correct, and then adding the necessary 25641@code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order. 25642 25643 25644@c ********************************** 25645@node Overflow Check Handling in GNAT 25646@appendix Overflow Check Handling in GNAT 25647@cindex Overflow checks 25648@cindex Checks (overflow) 25649@c ********************************** 25650 25651@menu 25652* Background:: 25653* Overflow Checking Modes in GNAT:: 25654* Specifying the Desired Mode:: 25655* Default Settings:: 25656* Implementation Notes:: 25657@end menu 25658 25659 25660@node Background 25661@section Background 25662 25663@noindent 25664Overflow checks are checks that the compiler may make to ensure 25665that intermediate results are not out of range. For example: 25666 25667@smallexample @c ada 25668 A : Integer; 25669 ... 25670 A := A + 1; 25671@end smallexample 25672 25673@noindent 25674if @code{A} has the value @code{Integer'Last}, then the addition may cause 25675overflow since the result is out of range of the type @code{Integer}. 25676In this case @code{Constraint_Error} will be raised if checks are 25677enabled. 25678 25679A trickier situation arises in examples like the following: 25680 25681@smallexample @c ada 25682 A, C : Integer; 25683 ... 25684 A := (A + 1) + C; 25685@end smallexample 25686 25687@noindent 25688where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}. 25689Now the final result of the expression on the right hand side is 25690@code{Integer'Last} which is in range, but the question arises whether the 25691intermediate addition of @code{(A + 1)} raises an overflow error. 25692 25693The (perhaps surprising) answer is that the Ada language 25694definition does not answer this question. Instead it leaves 25695it up to the implementation to do one of two things if overflow 25696checks are enabled. 25697 25698@itemize @bullet 25699@item 25700raise an exception (@code{Constraint_Error}), or 25701 25702@item 25703yield the correct mathematical result which is then used in 25704subsequent operations. 25705@end itemize 25706 25707@noindent 25708If the compiler chooses the first approach, then the assignment of this 25709example will indeed raise @code{Constraint_Error} if overflow checking is 25710enabled, or result in erroneous execution if overflow checks are suppressed. 25711 25712But if the compiler 25713chooses the second approach, then it can perform both additions yielding 25714the correct mathematical result, which is in range, so no exception 25715will be raised, and the right result is obtained, regardless of whether 25716overflow checks are suppressed. 25717 25718Note that in the first example an 25719exception will be raised in either case, since if the compiler 25720gives the correct mathematical result for the addition, it will 25721be out of range of the target type of the assignment, and thus 25722fails the range check. 25723 25724This lack of specified behavior in the handling of overflow for 25725intermediate results is a source of non-portability, and can thus 25726be problematic when programs are ported. Most typically this arises 25727in a situation where the original compiler did not raise an exception, 25728and then the application is moved to a compiler where the check is 25729performed on the intermediate result and an unexpected exception is 25730raised. 25731 25732Furthermore, when using Ada 2012's preconditions and other 25733assertion forms, another issue arises. Consider: 25734 25735@smallexample @c ada 25736 procedure P (A, B : Integer) with 25737 Pre => A + B <= Integer'Last; 25738@end smallexample 25739 25740@noindent 25741One often wants to regard arithmetic in a context like this from 25742a mathematical point of view. So for example, if the two actual parameters 25743for a call to @code{P} are both @code{Integer'Last}, then 25744the precondition should be regarded as False. If we are executing 25745in a mode with run-time checks enabled for preconditions, then we would 25746like this precondition to fail, rather than raising an exception 25747because of the intermediate overflow. 25748 25749However, the language definition leaves the specification of 25750whether the above condition fails (raising @code{Assert_Error}) or 25751causes an intermediate overflow (raising @code{Constraint_Error}) 25752up to the implementation. 25753 25754The situation is worse in a case such as the following: 25755 25756@smallexample @c ada 25757 procedure Q (A, B, C : Integer) with 25758 Pre => A + B + C <= Integer'Last; 25759@end smallexample 25760 25761@noindent 25762Consider the call 25763 25764@smallexample @c ada 25765 Q (A => Integer'Last, B => 1, C => -1); 25766@end smallexample 25767 25768@noindent 25769From a mathematical point of view the precondition 25770is True, but at run time we may (but are not guaranteed to) get an 25771exception raised because of the intermediate overflow (and we really 25772would prefer this precondition to be considered True at run time). 25773 25774@node Overflow Checking Modes in GNAT 25775@section Overflow Checking Modes in GNAT 25776 25777@noindent 25778To deal with the portability issue, and with the problem of 25779mathematical versus run-time intepretation of the expressions in 25780assertions, GNAT provides comprehensive control over the handling 25781of intermediate overflow. GNAT can operate in three modes, and 25782furthemore, permits separate selection of operating modes for 25783the expressions within assertions (here the term ``assertions'' 25784is used in the technical sense, which includes preconditions and so forth) 25785and for expressions appearing outside assertions. 25786 25787The three modes are: 25788 25789@itemize @bullet 25790@item @i{Use base type for intermediate operations} (@code{STRICT}) 25791 25792 In this mode, all intermediate results for predefined arithmetic 25793 operators are computed using the base type, and the result must 25794 be in range of the base type. If this is not the 25795 case then either an exception is raised (if overflow checks are 25796 enabled) or the execution is erroneous (if overflow checks are suppressed). 25797 This is the normal default mode. 25798 25799@item @i{Most intermediate overflows avoided} (@code{MINIMIZED}) 25800 25801 In this mode, the compiler attempts to avoid intermediate overflows by 25802 using a larger integer type, typically @code{Long_Long_Integer}, 25803 as the type in which arithmetic is 25804 performed for predefined arithmetic operators. This may be slightly more 25805 expensive at 25806 run time (compared to suppressing intermediate overflow checks), though 25807 the cost is negligible on modern 64-bit machines. For the examples given 25808 earlier, no intermediate overflows would have resulted in exceptions, 25809 since the intermediate results are all in the range of 25810 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations 25811 of GNAT). In addition, if checks are enabled, this reduces the number of 25812 checks that must be made, so this choice may actually result in an 25813 improvement in space and time behavior. 25814 25815 However, there are cases where @code{Long_Long_Integer} is not large 25816 enough, consider the following example: 25817 25818@smallexample @c ada 25819 procedure R (A, B, C, D : Integer) with 25820 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10; 25821@end smallexample 25822 25823 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}. 25824 Now the intermediate results are 25825 out of the range of @code{Long_Long_Integer} even though the final result 25826 is in range and the precondition is True (from a mathematical point 25827 of view). In such a case, operating in this mode, an overflow occurs 25828 for the intermediate computation (which is why this mode 25829 says @i{most} intermediate overflows are avoided). In this case, 25830 an exception is raised if overflow checks are enabled, and the 25831 execution is erroneous if overflow checks are suppressed. 25832 25833@item @i{All intermediate overflows avoided} (@code{ELIMINATED}) 25834 25835 In this mode, the compiler avoids all intermediate overflows 25836 by using arbitrary precision arithmetic as required. In this 25837 mode, the above example with @code{A**2 * B**2} would 25838 not cause intermediate overflow, because the intermediate result 25839 would be evaluated using sufficient precision, and the result 25840 of evaluating the precondition would be True. 25841 25842 This mode has the advantage of avoiding any intermediate 25843 overflows, but at the expense of significant run-time overhead, 25844 including the use of a library (included automatically in this 25845 mode) for multiple-precision arithmetic. 25846 25847 This mode provides cleaner semantics for assertions, since now 25848 the run-time behavior emulates true arithmetic behavior for the 25849 predefined arithmetic operators, meaning that there is never a 25850 conflict between the mathematical view of the assertion, and its 25851 run-time behavior. 25852 25853 Note that in this mode, the behavior is unaffected by whether or 25854 not overflow checks are suppressed, since overflow does not occur. 25855 It is possible for gigantic intermediate expressions to raise 25856 @code{Storage_Error} as a result of attempting to compute the 25857 results of such expressions (e.g. @code{Integer'Last ** Integer'Last}) 25858 but overflow is impossible. 25859 25860 25861@end itemize 25862 25863@noindent 25864 Note that these modes apply only to the evaluation of predefined 25865 arithmetic, membership, and comparison operators for signed integer 25866 aritmetic. 25867 25868 For fixed-point arithmetic, checks can be suppressed. But if checks 25869 are enabled 25870 then fixed-point values are always checked for overflow against the 25871 base type for intermediate expressions (that is such checks always 25872 operate in the equivalent of @code{STRICT} mode). 25873 25874 For floating-point, on nearly all architectures, @code{Machine_Overflows} 25875 is False, and IEEE infinities are generated, so overflow exceptions 25876 are never raised. If you want to avoid infinities, and check that 25877 final results of expressions are in range, then you can declare a 25878 constrained floating-point type, and range checks will be carried 25879 out in the normal manner (with infinite values always failing all 25880 range checks). 25881 25882 25883@c ------------------------- 25884@node Specifying the Desired Mode 25885@section Specifying the Desired Mode 25886 25887@noindent 25888The desired mode of for handling intermediate overflow can be specified using 25889either the @code{Overflow_Mode} pragma or an equivalent compiler switch. 25890The pragma has the form 25891@cindex pragma @code{Overflow_Mode} 25892 25893@smallexample @c ada 25894 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]); 25895@end smallexample 25896 25897@noindent 25898where @code{MODE} is one of 25899 25900@itemize @bullet 25901@item @code{STRICT}: intermediate overflows checked (using base type) 25902@item @code{MINIMIZED}: minimize intermediate overflows 25903@item @code{ELIMINATED}: eliminate intermediate overflows 25904@end itemize 25905 25906@noindent 25907The case is ignored, so @code{MINIMIZED}, @code{Minimized} and 25908@code{minimized} all have the same effect. 25909 25910If only the @code{General} parameter is present, then the given @code{MODE} 25911applies 25912to expressions both within and outside assertions. If both arguments 25913are present, then @code{General} applies to expressions outside assertions, 25914and @code{Assertions} applies to expressions within assertions. For example: 25915 25916@smallexample @c ada 25917 pragma Overflow_Mode 25918 (General => Minimized, Assertions => Eliminated); 25919@end smallexample 25920 25921@noindent 25922specifies that general expressions outside assertions be evaluated 25923in ``minimize intermediate overflows'' mode, and expressions within 25924assertions be evaluated in ``eliminate intermediate overflows'' mode. 25925This is often a reasonable choice, avoiding excessive overhead 25926outside assertions, but assuring a high degree of portability 25927when importing code from another compiler, while incurring 25928the extra overhead for assertion expressions to ensure that 25929the behavior at run time matches the expected mathematical 25930behavior. 25931 25932The @code{Overflow_Mode} pragma has the same scoping and placement 25933rules as pragma @code{Suppress}, so it can occur either as a 25934configuration pragma, specifying a default for the whole 25935program, or in a declarative scope, where it applies to the 25936remaining declarations and statements in that scope. 25937 25938Note that pragma @code{Overflow_Mode} does not affect whether 25939overflow checks are enabled or suppressed. It only controls the 25940method used to compute intermediate values. To control whether 25941overflow checking is enabled or suppressed, use pragma @code{Suppress} 25942or @code{Unsuppress} in the usual manner 25943 25944Additionally, a compiler switch @option{-gnato?} or @option{-gnato??} 25945can be used to control the checking mode default (which can be subsequently 25946overridden using pragmas). 25947@cindex @option{-gnato?} (gcc) 25948@cindex @option{-gnato??} (gcc) 25949 25950Here `@code{?}' is one of the digits `@code{1}' through `@code{3}': 25951 25952@itemize @bullet 25953@item @code{1}: 25954use base type for intermediate operations (@code{STRICT}) 25955@item @code{2}: 25956minimize intermediate overflows (@code{MINIMIZED}) 25957@item @code{3}: 25958eliminate intermediate overflows (@code{ELIMINATED}) 25959@end itemize 25960 25961@noindent 25962As with the pragma, if only one digit appears then it applies to all 25963cases; if two digits are given, then the first applies outside 25964assertions, and the second within assertions. Thus the equivalent 25965of the example pragma above would be @option{-gnato23}. 25966 25967If no digits follow the @option{-gnato}, then it is equivalent to 25968@option{-gnato11}, 25969causing all intermediate operations to be computed using the base 25970type (@code{STRICT} mode). 25971 25972In addition to setting the mode used for computation of intermediate 25973results, the @code{-gnato} switch also enables overflow checking (which 25974is suppressed by default). It thus combines the effect of using 25975a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}. 25976 25977 25978@c ------------------------- 25979@node Default Settings 25980@section Default Settings 25981 25982The default mode for overflow checks is 25983 25984@smallexample 25985 General => Strict 25986@end smallexample 25987 25988@noindent 25989which causes all computations both inside and outside assertions to use 25990the base type. In addition overflow checks are suppressed. 25991 25992This retains compatibility with previous versions of 25993GNAT which suppressed overflow checks by default and always 25994used the base type for computation of intermediate results. 25995 25996The switch @option{-gnato} (with no digits following) is equivalent to 25997@cindex @option{-gnato} (gcc) 25998 25999@smallexample 26000 General => Strict 26001@end smallexample 26002 26003@noindent 26004which causes overflow checking of all intermediate overflows 26005both inside and outside assertions against the base type. 26006This provides compatibility 26007with this switch as implemented in previous versions of GNAT. 26008 26009The pragma @code{Suppress (Overflow_Check)} disables overflow 26010checking, but it has no effect on the method used for computing 26011intermediate results. 26012 26013The pragma @code{Unsuppress (Overflow_Check)} enables overflow 26014checking, but it has no effect on the method used for computing 26015intermediate results. 26016 26017@c ------------------------- 26018@node Implementation Notes 26019@section Implementation Notes 26020 26021In practice on typical 64-bit machines, the @code{MINIMIZED} mode is 26022reasonably efficient, and can be generally used. It also helps 26023to ensure compatibility with code imported from some other 26024compiler to GNAT. 26025 26026Setting all intermediate overflows checking (@code{CHECKED} mode) 26027makes sense if you want to 26028make sure that your code is compatible with any other possible 26029Ada implementation. This may be useful in ensuring portability 26030for code that is to be exported to some other compiler than GNAT. 26031 26032 26033The Ada standard allows the reassociation of expressions at 26034the same precedence level if no parentheses are present. For 26035example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but 26036the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly 26037introducing or eliminating an overflow exception. The GNAT 26038compiler never takes advantage of this freedom, and the 26039expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}. 26040If you need the other order, you can write the parentheses 26041explicitly @w{@code{A+(B+C)}} and GNAT will respect this order. 26042 26043The use of @code{ELIMINATED} mode will cause the compiler to 26044automatically include an appropriate arbitrary precision 26045integer arithmetic package. The compiler will make calls 26046to this package, though only in cases where it cannot be 26047sure that @code{Long_Long_Integer} is sufficient to guard against 26048intermediate overflows. This package does not use dynamic 26049alllocation, but it does use the secondary stack, so an 26050appropriate secondary stack package must be present (this 26051is always true for standard full Ada, but may require 26052specific steps for restricted run times such as ZFP). 26053 26054Although @code{ELIMINATED} mode causes expressions to use arbitrary 26055precision arithmetic, avoiding overflow, the final result 26056must be in an appropriate range. This is true even if the 26057final result is of type @code{[Long_[Long_]]Integer'Base}, which 26058still has the same bounds as its associated constrained 26059type at run-time. 26060 26061Currently, the @code{ELIMINATED} mode is only available on target 26062platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT 26063platforms). 26064 26065@c ******************************* 26066@node Conditional Compilation 26067@appendix Conditional Compilation 26068@c ******************************* 26069@cindex Conditional compilation 26070 26071@noindent 26072It is often necessary to arrange for a single source program 26073to serve multiple purposes, where it is compiled in different 26074ways to achieve these different goals. Some examples of the 26075need for this feature are 26076 26077@itemize @bullet 26078@item Adapting a program to a different hardware environment 26079@item Adapting a program to a different target architecture 26080@item Turning debugging features on and off 26081@item Arranging for a program to compile with different compilers 26082@end itemize 26083 26084@noindent 26085In C, or C++, the typical approach would be to use the preprocessor 26086that is defined as part of the language. The Ada language does not 26087contain such a feature. This is not an oversight, but rather a very 26088deliberate design decision, based on the experience that overuse of 26089the preprocessing features in C and C++ can result in programs that 26090are extremely difficult to maintain. For example, if we have ten 26091switches that can be on or off, this means that there are a thousand 26092separate programs, any one of which might not even be syntactically 26093correct, and even if syntactically correct, the resulting program 26094might not work correctly. Testing all combinations can quickly become 26095impossible. 26096 26097Nevertheless, the need to tailor programs certainly exists, and in 26098this Appendix we will discuss how this can 26099be achieved using Ada in general, and GNAT in particular. 26100 26101@menu 26102* Use of Boolean Constants:: 26103* Debugging - A Special Case:: 26104* Conditionalizing Declarations:: 26105* Use of Alternative Implementations:: 26106* Preprocessing:: 26107@end menu 26108 26109@node Use of Boolean Constants 26110@section Use of Boolean Constants 26111 26112@noindent 26113In the case where the difference is simply which code 26114sequence is executed, the cleanest solution is to use Boolean 26115constants to control which code is executed. 26116 26117@smallexample @c ada 26118@group 26119FP_Initialize_Required : constant Boolean := True; 26120@dots{} 26121if FP_Initialize_Required then 26122@dots{} 26123end if; 26124@end group 26125@end smallexample 26126 26127@noindent 26128Not only will the code inside the @code{if} statement not be executed if 26129the constant Boolean is @code{False}, but it will also be completely 26130deleted from the program. 26131However, the code is only deleted after the @code{if} statement 26132has been checked for syntactic and semantic correctness. 26133(In contrast, with preprocessors the code is deleted before the 26134compiler ever gets to see it, so it is not checked until the switch 26135is turned on.) 26136@cindex Preprocessors (contrasted with conditional compilation) 26137 26138Typically the Boolean constants will be in a separate package, 26139something like: 26140 26141@smallexample @c ada 26142@group 26143package Config is 26144 FP_Initialize_Required : constant Boolean := True; 26145 Reset_Available : constant Boolean := False; 26146 @dots{} 26147end Config; 26148@end group 26149@end smallexample 26150 26151@noindent 26152The @code{Config} package exists in multiple forms for the various targets, 26153with an appropriate script selecting the version of @code{Config} needed. 26154Then any other unit requiring conditional compilation can do a @code{with} 26155of @code{Config} to make the constants visible. 26156 26157 26158@node Debugging - A Special Case 26159@section Debugging - A Special Case 26160 26161@noindent 26162A common use of conditional code is to execute statements (for example 26163dynamic checks, or output of intermediate results) under control of a 26164debug switch, so that the debugging behavior can be turned on and off. 26165This can be done using a Boolean constant to control whether the code 26166is active: 26167 26168@smallexample @c ada 26169@group 26170if Debugging then 26171 Put_Line ("got to the first stage!"); 26172end if; 26173@end group 26174@end smallexample 26175 26176@noindent 26177or 26178 26179@smallexample @c ada 26180@group 26181if Debugging and then Temperature > 999.0 then 26182 raise Temperature_Crazy; 26183end if; 26184@end group 26185@end smallexample 26186 26187@noindent 26188Since this is a common case, there are special features to deal with 26189this in a convenient manner. For the case of tests, Ada 2005 has added 26190a pragma @code{Assert} that can be used for such tests. This pragma is modeled 26191@cindex pragma @code{Assert} 26192on the @code{Assert} pragma that has always been available in GNAT, so this 26193feature may be used with GNAT even if you are not using Ada 2005 features. 26194The use of pragma @code{Assert} is described in 26195@ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an 26196example, the last test could be written: 26197 26198@smallexample @c ada 26199pragma Assert (Temperature <= 999.0, "Temperature Crazy"); 26200@end smallexample 26201 26202@noindent 26203or simply 26204 26205@smallexample @c ada 26206pragma Assert (Temperature <= 999.0); 26207@end smallexample 26208 26209@noindent 26210In both cases, if assertions are active and the temperature is excessive, 26211the exception @code{Assert_Failure} will be raised, with the given string in 26212the first case or a string indicating the location of the pragma in the second 26213case used as the exception message. 26214 26215You can turn assertions on and off by using the @code{Assertion_Policy} 26216pragma. 26217@cindex pragma @code{Assertion_Policy} 26218This is an Ada 2005 pragma which is implemented in all modes by 26219GNAT, but only in the latest versions of GNAT which include Ada 2005 26220capability. Alternatively, you can use the @option{-gnata} switch 26221@cindex @option{-gnata} switch 26222to enable assertions from the command line (this is recognized by all versions 26223of GNAT). 26224 26225For the example above with the @code{Put_Line}, the GNAT-specific pragma 26226@code{Debug} can be used: 26227@cindex pragma @code{Debug} 26228 26229@smallexample @c ada 26230pragma Debug (Put_Line ("got to the first stage!")); 26231@end smallexample 26232 26233@noindent 26234If debug pragmas are enabled, the argument, which must be of the form of 26235a procedure call, is executed (in this case, @code{Put_Line} will be called). 26236Only one call can be present, but of course a special debugging procedure 26237containing any code you like can be included in the program and then 26238called in a pragma @code{Debug} argument as needed. 26239 26240One advantage of pragma @code{Debug} over the @code{if Debugging then} 26241construct is that pragma @code{Debug} can appear in declarative contexts, 26242such as at the very beginning of a procedure, before local declarations have 26243been elaborated. 26244 26245Debug pragmas are enabled using either the @option{-gnata} switch that also 26246controls assertions, or with a separate Debug_Policy pragma. 26247@cindex pragma @code{Debug_Policy} 26248The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used 26249in Ada 95 and Ada 83 programs as well), and is analogous to 26250pragma @code{Assertion_Policy} to control assertions. 26251 26252@code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas, 26253and thus they can appear in @file{gnat.adc} if you are not using a 26254project file, or in the file designated to contain configuration pragmas 26255in a project file. 26256They then apply to all subsequent compilations. In practice the use of 26257the @option{-gnata} switch is often the most convenient method of controlling 26258the status of these pragmas. 26259 26260Note that a pragma is not a statement, so in contexts where a statement 26261sequence is required, you can't just write a pragma on its own. You have 26262to add a @code{null} statement. 26263 26264@smallexample @c ada 26265@group 26266if @dots{} then 26267 @dots{} -- some statements 26268else 26269 pragma Assert (Num_Cases < 10); 26270 null; 26271end if; 26272@end group 26273@end smallexample 26274 26275 26276@node Conditionalizing Declarations 26277@section Conditionalizing Declarations 26278 26279@noindent 26280In some cases, it may be necessary to conditionalize declarations to meet 26281different requirements. For example we might want a bit string whose length 26282is set to meet some hardware message requirement. 26283 26284In some cases, it may be possible to do this using declare blocks controlled 26285by conditional constants: 26286 26287@smallexample @c ada 26288@group 26289if Small_Machine then 26290 declare 26291 X : Bit_String (1 .. 10); 26292 begin 26293 @dots{} 26294 end; 26295else 26296 declare 26297 X : Large_Bit_String (1 .. 1000); 26298 begin 26299 @dots{} 26300 end; 26301end if; 26302@end group 26303@end smallexample 26304 26305@noindent 26306Note that in this approach, both declarations are analyzed by the 26307compiler so this can only be used where both declarations are legal, 26308even though one of them will not be used. 26309 26310Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word}, 26311or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations 26312that are parameterized by these constants. For example 26313 26314@smallexample @c ada 26315@group 26316for Rec use 26317 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word; 26318end record; 26319@end group 26320@end smallexample 26321 26322@noindent 26323If @code{Bits_Per_Word} is set to 32, this generates either 26324 26325@smallexample @c ada 26326@group 26327for Rec use 26328 Field1 at 0 range 0 .. 32; 26329end record; 26330@end group 26331@end smallexample 26332 26333@noindent 26334for the big endian case, or 26335 26336@smallexample @c ada 26337@group 26338for Rec use record 26339 Field1 at 0 range 10 .. 32; 26340end record; 26341@end group 26342@end smallexample 26343 26344@noindent 26345for the little endian case. Since a powerful subset of Ada expression 26346notation is usable for creating static constants, clever use of this 26347feature can often solve quite difficult problems in conditionalizing 26348compilation (note incidentally that in Ada 95, the little endian 26349constant was introduced as @code{System.Default_Bit_Order}, so you do not 26350need to define this one yourself). 26351 26352 26353@node Use of Alternative Implementations 26354@section Use of Alternative Implementations 26355 26356@noindent 26357In some cases, none of the approaches described above are adequate. This 26358can occur for example if the set of declarations required is radically 26359different for two different configurations. 26360 26361In this situation, the official Ada way of dealing with conditionalizing 26362such code is to write separate units for the different cases. As long as 26363this does not result in excessive duplication of code, this can be done 26364without creating maintenance problems. The approach is to share common 26365code as far as possible, and then isolate the code and declarations 26366that are different. Subunits are often a convenient method for breaking 26367out a piece of a unit that is to be conditionalized, with separate files 26368for different versions of the subunit for different targets, where the 26369build script selects the right one to give to the compiler. 26370@cindex Subunits (and conditional compilation) 26371 26372As an example, consider a situation where a new feature in Ada 2005 26373allows something to be done in a really nice way. But your code must be able 26374to compile with an Ada 95 compiler. Conceptually you want to say: 26375 26376@smallexample @c ada 26377@group 26378if Ada_2005 then 26379 @dots{} neat Ada 2005 code 26380else 26381 @dots{} not quite as neat Ada 95 code 26382end if; 26383@end group 26384@end smallexample 26385 26386@noindent 26387where @code{Ada_2005} is a Boolean constant. 26388 26389But this won't work when @code{Ada_2005} is set to @code{False}, 26390since the @code{then} clause will be illegal for an Ada 95 compiler. 26391(Recall that although such unreachable code would eventually be deleted 26392by the compiler, it still needs to be legal. If it uses features 26393introduced in Ada 2005, it will be illegal in Ada 95.) 26394 26395So instead we write 26396 26397@smallexample @c ada 26398procedure Insert is separate; 26399@end smallexample 26400 26401@noindent 26402Then we have two files for the subunit @code{Insert}, with the two sets of 26403code. 26404If the package containing this is called @code{File_Queries}, then we might 26405have two files 26406 26407@itemize @bullet 26408@item @file{file_queries-insert-2005.adb} 26409@item @file{file_queries-insert-95.adb} 26410@end itemize 26411 26412@noindent 26413and the build script renames the appropriate file to 26414 26415@smallexample 26416file_queries-insert.adb 26417@end smallexample 26418 26419@noindent 26420and then carries out the compilation. 26421 26422This can also be done with project files' naming schemes. For example: 26423 26424@smallexample @c project 26425For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada"; 26426@end smallexample 26427 26428@noindent 26429Note also that with project files it is desirable to use a different extension 26430than @file{ads} / @file{adb} for alternative versions. Otherwise a naming 26431conflict may arise through another commonly used feature: to declare as part 26432of the project a set of directories containing all the sources obeying the 26433default naming scheme. 26434 26435The use of alternative units is certainly feasible in all situations, 26436and for example the Ada part of the GNAT run-time is conditionalized 26437based on the target architecture using this approach. As a specific example, 26438consider the implementation of the AST feature in VMS. There is one 26439spec: 26440 26441@smallexample 26442s-asthan.ads 26443@end smallexample 26444 26445@noindent 26446which is the same for all architectures, and three bodies: 26447 26448@table @file 26449@item s-asthan.adb 26450used for all non-VMS operating systems 26451@item s-asthan-vms-alpha.adb 26452used for VMS on the Alpha 26453@item s-asthan-vms-ia64.adb 26454used for VMS on the ia64 26455@end table 26456 26457@noindent 26458The dummy version @file{s-asthan.adb} simply raises exceptions noting that 26459this operating system feature is not available, and the two remaining 26460versions interface with the corresponding versions of VMS to provide 26461VMS-compatible AST handling. The GNAT build script knows the architecture 26462and operating system, and automatically selects the right version, 26463renaming it if necessary to @file{s-asthan.adb} before the run-time build. 26464 26465Another style for arranging alternative implementations is through Ada's 26466access-to-subprogram facility. 26467In case some functionality is to be conditionally included, 26468you can declare an access-to-procedure variable @code{Ref} that is initialized 26469to designate a ``do nothing'' procedure, and then invoke @code{Ref.all} 26470when appropriate. 26471In some library package, set @code{Ref} to @code{Proc'Access} for some 26472procedure @code{Proc} that performs the relevant processing. 26473The initialization only occurs if the library package is included in the 26474program. 26475The same idea can also be implemented using tagged types and dispatching 26476calls. 26477 26478 26479@node Preprocessing 26480@section Preprocessing 26481@cindex Preprocessing 26482 26483@noindent 26484Although it is quite possible to conditionalize code without the use of 26485C-style preprocessing, as described earlier in this section, it is 26486nevertheless convenient in some cases to use the C approach. Moreover, 26487older Ada compilers have often provided some preprocessing capability, 26488so legacy code may depend on this approach, even though it is not 26489standard. 26490 26491To accommodate such use, GNAT provides a preprocessor (modeled to a large 26492extent on the various preprocessors that have been used 26493with legacy code on other compilers, to enable easier transition). 26494 26495The preprocessor may be used in two separate modes. It can be used quite 26496separately from the compiler, to generate a separate output source file 26497that is then fed to the compiler as a separate step. This is the 26498@code{gnatprep} utility, whose use is fully described in 26499@ref{Preprocessing Using gnatprep}. 26500@cindex @code{gnatprep} 26501 26502The preprocessing language allows such constructs as 26503 26504@smallexample 26505@group 26506#if DEBUG or PRIORITY > 4 then 26507 bunch of declarations 26508#else 26509 completely different bunch of declarations 26510#end if; 26511@end group 26512@end smallexample 26513 26514@noindent 26515The values of the symbols @code{DEBUG} and @code{PRIORITY} can be 26516defined either on the command line or in a separate file. 26517 26518The other way of running the preprocessor is even closer to the C style and 26519often more convenient. In this approach the preprocessing is integrated into 26520the compilation process. The compiler is fed the preprocessor input which 26521includes @code{#if} lines etc, and then the compiler carries out the 26522preprocessing internally and processes the resulting output. 26523For more details on this approach, see @ref{Integrated Preprocessing}. 26524 26525 26526@c ******************************* 26527@node Inline Assembler 26528@appendix Inline Assembler 26529@c ******************************* 26530 26531@noindent 26532If you need to write low-level software that interacts directly 26533with the hardware, Ada provides two ways to incorporate assembly 26534language code into your program. First, you can import and invoke 26535external routines written in assembly language, an Ada feature fully 26536supported by GNAT@. However, for small sections of code it may be simpler 26537or more efficient to include assembly language statements directly 26538in your Ada source program, using the facilities of the implementation-defined 26539package @code{System.Machine_Code}, which incorporates the gcc 26540Inline Assembler. The Inline Assembler approach offers a number of advantages, 26541including the following: 26542 26543@itemize @bullet 26544@item No need to use non-Ada tools 26545@item Consistent interface over different targets 26546@item Automatic usage of the proper calling conventions 26547@item Access to Ada constants and variables 26548@item Definition of intrinsic routines 26549@item Possibility of inlining a subprogram comprising assembler code 26550@item Code optimizer can take Inline Assembler code into account 26551@end itemize 26552 26553This chapter presents a series of examples to show you how to use 26554the Inline Assembler. Although it focuses on the Intel x86, 26555the general approach applies also to other processors. 26556It is assumed that you are familiar with Ada 26557and with assembly language programming. 26558 26559@menu 26560* Basic Assembler Syntax:: 26561* A Simple Example of Inline Assembler:: 26562* Output Variables in Inline Assembler:: 26563* Input Variables in Inline Assembler:: 26564* Inlining Inline Assembler Code:: 26565* Other Asm Functionality:: 26566@end menu 26567 26568@c --------------------------------------------------------------------------- 26569@node Basic Assembler Syntax 26570@section Basic Assembler Syntax 26571 26572@noindent 26573The assembler used by GNAT and gcc is based not on the Intel assembly 26574language, but rather on a language that descends from the AT&T Unix 26575assembler @emph{as} (and which is often referred to as ``AT&T syntax''). 26576The following table summarizes the main features of @emph{as} syntax 26577and points out the differences from the Intel conventions. 26578See the gcc @emph{as} and @emph{gas} (an @emph{as} macro 26579pre-processor) documentation for further information. 26580 26581@table @asis 26582@item Register names 26583gcc / @emph{as}: Prefix with ``%''; for example @code{%eax} 26584@* 26585Intel: No extra punctuation; for example @code{eax} 26586 26587@item Immediate operand 26588gcc / @emph{as}: Prefix with ``$''; for example @code{$4} 26589@* 26590Intel: No extra punctuation; for example @code{4} 26591 26592@item Address 26593gcc / @emph{as}: Prefix with ``$''; for example @code{$loc} 26594@* 26595Intel: No extra punctuation; for example @code{loc} 26596 26597@item Memory contents 26598gcc / @emph{as}: No extra punctuation; for example @code{loc} 26599@* 26600Intel: Square brackets; for example @code{[loc]} 26601 26602@item Register contents 26603gcc / @emph{as}: Parentheses; for example @code{(%eax)} 26604@* 26605Intel: Square brackets; for example @code{[eax]} 26606 26607@item Hexadecimal numbers 26608gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0} 26609@* 26610Intel: Trailing ``h''; for example @code{A0h} 26611 26612@item Operand size 26613gcc / @emph{as}: Explicit in op code; for example @code{movw} to move 26614a 16-bit word 26615@* 26616Intel: Implicit, deduced by assembler; for example @code{mov} 26617 26618@item Instruction repetition 26619gcc / @emph{as}: Split into two lines; for example 26620@* 26621@code{rep} 26622@* 26623@code{stosl} 26624@* 26625Intel: Keep on one line; for example @code{rep stosl} 26626 26627@item Order of operands 26628gcc / @emph{as}: Source first; for example @code{movw $4, %eax} 26629@* 26630Intel: Destination first; for example @code{mov eax, 4} 26631@end table 26632 26633@c --------------------------------------------------------------------------- 26634@node A Simple Example of Inline Assembler 26635@section A Simple Example of Inline Assembler 26636 26637@noindent 26638The following example will generate a single assembly language statement, 26639@code{nop}, which does nothing. Despite its lack of run-time effect, 26640the example will be useful in illustrating the basics of 26641the Inline Assembler facility. 26642 26643@smallexample @c ada 26644@group 26645with System.Machine_Code; use System.Machine_Code; 26646procedure Nothing is 26647begin 26648 Asm ("nop"); 26649end Nothing; 26650@end group 26651@end smallexample 26652 26653@code{Asm} is a procedure declared in package @code{System.Machine_Code}; 26654here it takes one parameter, a @emph{template string} that must be a static 26655expression and that will form the generated instruction. 26656@code{Asm} may be regarded as a compile-time procedure that parses 26657the template string and additional parameters (none here), 26658from which it generates a sequence of assembly language instructions. 26659 26660The examples in this chapter will illustrate several of the forms 26661for invoking @code{Asm}; a complete specification of the syntax 26662is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference 26663Manual}. 26664 26665Under the standard GNAT conventions, the @code{Nothing} procedure 26666should be in a file named @file{nothing.adb}. 26667You can build the executable in the usual way: 26668@smallexample 26669gnatmake nothing 26670@end smallexample 26671However, the interesting aspect of this example is not its run-time behavior 26672but rather the generated assembly code. 26673To see this output, invoke the compiler as follows: 26674@smallexample 26675 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb} 26676@end smallexample 26677where the options are: 26678 26679@table @code 26680@item -c 26681compile only (no bind or link) 26682@item -S 26683generate assembler listing 26684@item -fomit-frame-pointer 26685do not set up separate stack frames 26686@item -gnatp 26687do not add runtime checks 26688@end table 26689 26690This gives a human-readable assembler version of the code. The resulting 26691file will have the same name as the Ada source file, but with a @code{.s} 26692extension. In our example, the file @file{nothing.s} has the following 26693contents: 26694 26695@smallexample 26696@group 26697.file "nothing.adb" 26698gcc2_compiled.: 26699___gnu_compiled_ada: 26700.text 26701 .align 4 26702.globl __ada_nothing 26703__ada_nothing: 26704#APP 26705 nop 26706#NO_APP 26707 jmp L1 26708 .align 2,0x90 26709L1: 26710 ret 26711@end group 26712@end smallexample 26713 26714The assembly code you included is clearly indicated by 26715the compiler, between the @code{#APP} and @code{#NO_APP} 26716delimiters. The character before the 'APP' and 'NOAPP' 26717can differ on different targets. For example, GNU/Linux uses '#APP' while 26718on NT you will see '/APP'. 26719 26720If you make a mistake in your assembler code (such as using the 26721wrong size modifier, or using a wrong operand for the instruction) GNAT 26722will report this error in a temporary file, which will be deleted when 26723the compilation is finished. Generating an assembler file will help 26724in such cases, since you can assemble this file separately using the 26725@emph{as} assembler that comes with gcc. 26726 26727Assembling the file using the command 26728 26729@smallexample 26730as @file{nothing.s} 26731@end smallexample 26732@noindent 26733will give you error messages whose lines correspond to the assembler 26734input file, so you can easily find and correct any mistakes you made. 26735If there are no errors, @emph{as} will generate an object file 26736@file{nothing.out}. 26737 26738@c --------------------------------------------------------------------------- 26739@node Output Variables in Inline Assembler 26740@section Output Variables in Inline Assembler 26741 26742@noindent 26743The examples in this section, showing how to access the processor flags, 26744illustrate how to specify the destination operands for assembly language 26745statements. 26746 26747@smallexample @c ada 26748@group 26749with Interfaces; use Interfaces; 26750with Ada.Text_IO; use Ada.Text_IO; 26751with System.Machine_Code; use System.Machine_Code; 26752procedure Get_Flags is 26753 Flags : Unsigned_32; 26754 use ASCII; 26755begin 26756 Asm ("pushfl" & LF & HT & -- push flags on stack 26757 "popl %%eax" & LF & HT & -- load eax with flags 26758 "movl %%eax, %0", -- store flags in variable 26759 Outputs => Unsigned_32'Asm_Output ("=g", Flags)); 26760 Put_Line ("Flags register:" & Flags'Img); 26761end Get_Flags; 26762@end group 26763@end smallexample 26764 26765In order to have a nicely aligned assembly listing, we have separated 26766multiple assembler statements in the Asm template string with linefeed 26767(ASCII.LF) and horizontal tab (ASCII.HT) characters. 26768The resulting section of the assembly output file is: 26769 26770@smallexample 26771@group 26772#APP 26773 pushfl 26774 popl %eax 26775 movl %eax, -40(%ebp) 26776#NO_APP 26777@end group 26778@end smallexample 26779 26780It would have been legal to write the Asm invocation as: 26781 26782@smallexample 26783Asm ("pushfl popl %%eax movl %%eax, %0") 26784@end smallexample 26785 26786but in the generated assembler file, this would come out as: 26787 26788@smallexample 26789#APP 26790 pushfl popl %eax movl %eax, -40(%ebp) 26791#NO_APP 26792@end smallexample 26793 26794which is not so convenient for the human reader. 26795 26796We use Ada comments 26797at the end of each line to explain what the assembler instructions 26798actually do. This is a useful convention. 26799 26800When writing Inline Assembler instructions, you need to precede each register 26801and variable name with a percent sign. Since the assembler already requires 26802a percent sign at the beginning of a register name, you need two consecutive 26803percent signs for such names in the Asm template string, thus @code{%%eax}. 26804In the generated assembly code, one of the percent signs will be stripped off. 26805 26806Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output 26807variables: operands you later define using @code{Input} or @code{Output} 26808parameters to @code{Asm}. 26809An output variable is illustrated in 26810the third statement in the Asm template string: 26811@smallexample 26812movl %%eax, %0 26813@end smallexample 26814The intent is to store the contents of the eax register in a variable that can 26815be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not 26816necessarily work, since the compiler might optimize by using a register 26817to hold Flags, and the expansion of the @code{movl} instruction would not be 26818aware of this optimization. The solution is not to store the result directly 26819but rather to advise the compiler to choose the correct operand form; 26820that is the purpose of the @code{%0} output variable. 26821 26822Information about the output variable is supplied in the @code{Outputs} 26823parameter to @code{Asm}: 26824@smallexample 26825Outputs => Unsigned_32'Asm_Output ("=g", Flags)); 26826@end smallexample 26827 26828The output is defined by the @code{Asm_Output} attribute of the target type; 26829the general format is 26830@smallexample 26831Type'Asm_Output (constraint_string, variable_name) 26832@end smallexample 26833 26834The constraint string directs the compiler how 26835to store/access the associated variable. In the example 26836@smallexample 26837Unsigned_32'Asm_Output ("=m", Flags); 26838@end smallexample 26839the @code{"m"} (memory) constraint tells the compiler that the variable 26840@code{Flags} should be stored in a memory variable, thus preventing 26841the optimizer from keeping it in a register. In contrast, 26842@smallexample 26843Unsigned_32'Asm_Output ("=r", Flags); 26844@end smallexample 26845uses the @code{"r"} (register) constraint, telling the compiler to 26846store the variable in a register. 26847 26848If the constraint is preceded by the equal character (@strong{=}), it tells 26849the compiler that the variable will be used to store data into it. 26850 26851In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint, 26852allowing the optimizer to choose whatever it deems best. 26853 26854There are a fairly large number of constraints, but the ones that are 26855most useful (for the Intel x86 processor) are the following: 26856 26857@table @code 26858@item = 26859output constraint 26860@item g 26861global (i.e.@: can be stored anywhere) 26862@item m 26863in memory 26864@item I 26865a constant 26866@item a 26867use eax 26868@item b 26869use ebx 26870@item c 26871use ecx 26872@item d 26873use edx 26874@item S 26875use esi 26876@item D 26877use edi 26878@item r 26879use one of eax, ebx, ecx or edx 26880@item q 26881use one of eax, ebx, ecx, edx, esi or edi 26882@end table 26883 26884The full set of constraints is described in the gcc and @emph{as} 26885documentation; note that it is possible to combine certain constraints 26886in one constraint string. 26887 26888You specify the association of an output variable with an assembler operand 26889through the @code{%}@emph{n} notation, where @emph{n} is a non-negative 26890integer. Thus in 26891@smallexample @c ada 26892@group 26893Asm ("pushfl" & LF & HT & -- push flags on stack 26894 "popl %%eax" & LF & HT & -- load eax with flags 26895 "movl %%eax, %0", -- store flags in variable 26896 Outputs => Unsigned_32'Asm_Output ("=g", Flags)); 26897@end group 26898@end smallexample 26899@noindent 26900@code{%0} will be replaced in the expanded code by the appropriate operand, 26901whatever 26902the compiler decided for the @code{Flags} variable. 26903 26904In general, you may have any number of output variables: 26905@itemize @bullet 26906@item 26907Count the operands starting at 0; thus @code{%0}, @code{%1}, etc. 26908@item 26909Specify the @code{Outputs} parameter as a parenthesized comma-separated list 26910of @code{Asm_Output} attributes 26911@end itemize 26912 26913For example: 26914@smallexample @c ada 26915@group 26916Asm ("movl %%eax, %0" & LF & HT & 26917 "movl %%ebx, %1" & LF & HT & 26918 "movl %%ecx, %2", 26919 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A 26920 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B 26921 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C 26922@end group 26923@end smallexample 26924@noindent 26925where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables 26926in the Ada program. 26927 26928As a variation on the @code{Get_Flags} example, we can use the constraints 26929string to direct the compiler to store the eax register into the @code{Flags} 26930variable, instead of including the store instruction explicitly in the 26931@code{Asm} template string: 26932 26933@smallexample @c ada 26934@group 26935with Interfaces; use Interfaces; 26936with Ada.Text_IO; use Ada.Text_IO; 26937with System.Machine_Code; use System.Machine_Code; 26938procedure Get_Flags_2 is 26939 Flags : Unsigned_32; 26940 use ASCII; 26941begin 26942 Asm ("pushfl" & LF & HT & -- push flags on stack 26943 "popl %%eax", -- save flags in eax 26944 Outputs => Unsigned_32'Asm_Output ("=a", Flags)); 26945 Put_Line ("Flags register:" & Flags'Img); 26946end Get_Flags_2; 26947@end group 26948@end smallexample 26949 26950@noindent 26951The @code{"a"} constraint tells the compiler that the @code{Flags} 26952variable will come from the eax register. Here is the resulting code: 26953 26954@smallexample 26955@group 26956#APP 26957 pushfl 26958 popl %eax 26959#NO_APP 26960 movl %eax,-40(%ebp) 26961@end group 26962@end smallexample 26963 26964@noindent 26965The compiler generated the store of eax into Flags after 26966expanding the assembler code. 26967 26968Actually, there was no need to pop the flags into the eax register; 26969more simply, we could just pop the flags directly into the program variable: 26970 26971@smallexample @c ada 26972@group 26973with Interfaces; use Interfaces; 26974with Ada.Text_IO; use Ada.Text_IO; 26975with System.Machine_Code; use System.Machine_Code; 26976procedure Get_Flags_3 is 26977 Flags : Unsigned_32; 26978 use ASCII; 26979begin 26980 Asm ("pushfl" & LF & HT & -- push flags on stack 26981 "pop %0", -- save flags in Flags 26982 Outputs => Unsigned_32'Asm_Output ("=g", Flags)); 26983 Put_Line ("Flags register:" & Flags'Img); 26984end Get_Flags_3; 26985@end group 26986@end smallexample 26987 26988@c --------------------------------------------------------------------------- 26989@node Input Variables in Inline Assembler 26990@section Input Variables in Inline Assembler 26991 26992@noindent 26993The example in this section illustrates how to specify the source operands 26994for assembly language statements. 26995The program simply increments its input value by 1: 26996 26997@smallexample @c ada 26998@group 26999with Interfaces; use Interfaces; 27000with Ada.Text_IO; use Ada.Text_IO; 27001with System.Machine_Code; use System.Machine_Code; 27002procedure Increment is 27003 27004 function Incr (Value : Unsigned_32) return Unsigned_32 is 27005 Result : Unsigned_32; 27006 begin 27007 Asm ("incl %0", 27008 Outputs => Unsigned_32'Asm_Output ("=a", Result), 27009 Inputs => Unsigned_32'Asm_Input ("a", Value)); 27010 return Result; 27011 end Incr; 27012 27013 Value : Unsigned_32; 27014 27015begin 27016 Value := 5; 27017 Put_Line ("Value before is" & Value'Img); 27018 Value := Incr (Value); 27019 Put_Line ("Value after is" & Value'Img); 27020end Increment; 27021@end group 27022@end smallexample 27023 27024The @code{Outputs} parameter to @code{Asm} specifies 27025that the result will be in the eax register and that it is to be stored 27026in the @code{Result} variable. 27027 27028The @code{Inputs} parameter looks much like the @code{Outputs} parameter, 27029but with an @code{Asm_Input} attribute. 27030The @code{"="} constraint, indicating an output value, is not present. 27031 27032You can have multiple input variables, in the same way that you can have more 27033than one output variable. 27034 27035The parameter count (%0, %1) etc, still starts at the first output statement, 27036and continues with the input statements. 27037 27038Just as the @code{Outputs} parameter causes the register to be stored into the 27039target variable after execution of the assembler statements, so does the 27040@code{Inputs} parameter cause its variable to be loaded into the register 27041before execution of the assembler statements. 27042 27043Thus the effect of the @code{Asm} invocation is: 27044@enumerate 27045@item load the 32-bit value of @code{Value} into eax 27046@item execute the @code{incl %eax} instruction 27047@item store the contents of eax into the @code{Result} variable 27048@end enumerate 27049 27050The resulting assembler file (with @option{-O2} optimization) contains: 27051@smallexample 27052@group 27053_increment__incr.1: 27054 subl $4,%esp 27055 movl 8(%esp),%eax 27056#APP 27057 incl %eax 27058#NO_APP 27059 movl %eax,%edx 27060 movl %ecx,(%esp) 27061 addl $4,%esp 27062 ret 27063@end group 27064@end smallexample 27065 27066@c --------------------------------------------------------------------------- 27067@node Inlining Inline Assembler Code 27068@section Inlining Inline Assembler Code 27069 27070@noindent 27071For a short subprogram such as the @code{Incr} function in the previous 27072section, the overhead of the call and return (creating / deleting the stack 27073frame) can be significant, compared to the amount of code in the subprogram 27074body. A solution is to apply Ada's @code{Inline} pragma to the subprogram, 27075which directs the compiler to expand invocations of the subprogram at the 27076point(s) of call, instead of setting up a stack frame for out-of-line calls. 27077Here is the resulting program: 27078 27079@smallexample @c ada 27080@group 27081with Interfaces; use Interfaces; 27082with Ada.Text_IO; use Ada.Text_IO; 27083with System.Machine_Code; use System.Machine_Code; 27084procedure Increment_2 is 27085 27086 function Incr (Value : Unsigned_32) return Unsigned_32 is 27087 Result : Unsigned_32; 27088 begin 27089 Asm ("incl %0", 27090 Outputs => Unsigned_32'Asm_Output ("=a", Result), 27091 Inputs => Unsigned_32'Asm_Input ("a", Value)); 27092 return Result; 27093 end Incr; 27094 pragma Inline (Increment); 27095 27096 Value : Unsigned_32; 27097 27098begin 27099 Value := 5; 27100 Put_Line ("Value before is" & Value'Img); 27101 Value := Increment (Value); 27102 Put_Line ("Value after is" & Value'Img); 27103end Increment_2; 27104@end group 27105@end smallexample 27106 27107Compile the program with both optimization (@option{-O2}) and inlining 27108(@option{-gnatn}) enabled. 27109 27110The @code{Incr} function is still compiled as usual, but at the 27111point in @code{Increment} where our function used to be called: 27112 27113@smallexample 27114@group 27115pushl %edi 27116call _increment__incr.1 27117@end group 27118@end smallexample 27119 27120@noindent 27121the code for the function body directly appears: 27122 27123@smallexample 27124@group 27125movl %esi,%eax 27126#APP 27127 incl %eax 27128#NO_APP 27129 movl %eax,%edx 27130@end group 27131@end smallexample 27132 27133@noindent 27134thus saving the overhead of stack frame setup and an out-of-line call. 27135 27136@c --------------------------------------------------------------------------- 27137@node Other Asm Functionality 27138@section Other @code{Asm} Functionality 27139 27140@noindent 27141This section describes two important parameters to the @code{Asm} 27142procedure: @code{Clobber}, which identifies register usage; 27143and @code{Volatile}, which inhibits unwanted optimizations. 27144 27145@menu 27146* The Clobber Parameter:: 27147* The Volatile Parameter:: 27148@end menu 27149 27150@c --------------------------------------------------------------------------- 27151@node The Clobber Parameter 27152@subsection The @code{Clobber} Parameter 27153 27154@noindent 27155One of the dangers of intermixing assembly language and a compiled language 27156such as Ada is that the compiler needs to be aware of which registers are 27157being used by the assembly code. In some cases, such as the earlier examples, 27158the constraint string is sufficient to indicate register usage (e.g., 27159@code{"a"} for 27160the eax register). But more generally, the compiler needs an explicit 27161identification of the registers that are used by the Inline Assembly 27162statements. 27163 27164Using a register that the compiler doesn't know about 27165could be a side effect of an instruction (like @code{mull} 27166storing its result in both eax and edx). 27167It can also arise from explicit register usage in your 27168assembly code; for example: 27169@smallexample 27170@group 27171Asm ("movl %0, %%ebx" & LF & HT & 27172 "movl %%ebx, %1", 27173 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), 27174 Inputs => Unsigned_32'Asm_Input ("g", Var_In)); 27175@end group 27176@end smallexample 27177@noindent 27178where the compiler (since it does not analyze the @code{Asm} template string) 27179does not know you are using the ebx register. 27180 27181In such cases you need to supply the @code{Clobber} parameter to @code{Asm}, 27182to identify the registers that will be used by your assembly code: 27183 27184@smallexample 27185@group 27186Asm ("movl %0, %%ebx" & LF & HT & 27187 "movl %%ebx, %1", 27188 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), 27189 Inputs => Unsigned_32'Asm_Input ("g", Var_In), 27190 Clobber => "ebx"); 27191@end group 27192@end smallexample 27193 27194The Clobber parameter is a static string expression specifying the 27195register(s) you are using. Note that register names are @emph{not} prefixed 27196by a percent sign. Also, if more than one register is used then their names 27197are separated by commas; e.g., @code{"eax, ebx"} 27198 27199The @code{Clobber} parameter has several additional uses: 27200@enumerate 27201@item Use ``register'' name @code{cc} to indicate that flags might have changed 27202@item Use ``register'' name @code{memory} if you changed a memory location 27203@end enumerate 27204 27205@c --------------------------------------------------------------------------- 27206@node The Volatile Parameter 27207@subsection The @code{Volatile} Parameter 27208@cindex Volatile parameter 27209 27210@noindent 27211Compiler optimizations in the presence of Inline Assembler may sometimes have 27212unwanted effects. For example, when an @code{Asm} invocation with an input 27213variable is inside a loop, the compiler might move the loading of the input 27214variable outside the loop, regarding it as a one-time initialization. 27215 27216If this effect is not desired, you can disable such optimizations by setting 27217the @code{Volatile} parameter to @code{True}; for example: 27218 27219@smallexample @c ada 27220@group 27221Asm ("movl %0, %%ebx" & LF & HT & 27222 "movl %%ebx, %1", 27223 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out), 27224 Inputs => Unsigned_32'Asm_Input ("g", Var_In), 27225 Clobber => "ebx", 27226 Volatile => True); 27227@end group 27228@end smallexample 27229 27230By default, @code{Volatile} is set to @code{False} unless there is no 27231@code{Outputs} parameter. 27232 27233Although setting @code{Volatile} to @code{True} prevents unwanted 27234optimizations, it will also disable other optimizations that might be 27235important for efficiency. In general, you should set @code{Volatile} 27236to @code{True} only if the compiler's optimizations have created 27237problems. 27238@c END OF INLINE ASSEMBLER CHAPTER 27239@c =============================== 27240 27241@c *********************************** 27242@c * Compatibility and Porting Guide * 27243@c *********************************** 27244@node Compatibility and Porting Guide 27245@appendix Compatibility and Porting Guide 27246 27247@noindent 27248This chapter describes the compatibility issues that may arise between 27249GNAT and other Ada compilation systems (including those for Ada 83), 27250and shows how GNAT can expedite porting 27251applications developed in other Ada environments. 27252 27253@menu 27254* Compatibility with Ada 83:: 27255* Compatibility between Ada 95 and Ada 2005:: 27256* Implementation-dependent characteristics:: 27257* Compatibility with Other Ada Systems:: 27258* Representation Clauses:: 27259@ifclear vms 27260@c Brief section is only in non-VMS version 27261@c Full chapter is in VMS version 27262* Compatibility with HP Ada 83:: 27263@end ifclear 27264@ifset vms 27265* Transitioning to 64-Bit GNAT for OpenVMS:: 27266@end ifset 27267@end menu 27268 27269@node Compatibility with Ada 83 27270@section Compatibility with Ada 83 27271@cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005) 27272 27273@noindent 27274Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In 27275particular, the design intention was that the difficulties associated 27276with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those 27277that occur when moving from one Ada 83 system to another. 27278 27279However, there are a number of points at which there are minor 27280incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains 27281full details of these issues, 27282and should be consulted for a complete treatment. 27283In practice the 27284following subsections treat the most likely issues to be encountered. 27285 27286@menu 27287* Legal Ada 83 programs that are illegal in Ada 95:: 27288* More deterministic semantics:: 27289* Changed semantics:: 27290* Other language compatibility issues:: 27291@end menu 27292 27293@node Legal Ada 83 programs that are illegal in Ada 95 27294@subsection Legal Ada 83 programs that are illegal in Ada 95 27295 27296Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in 27297Ada 95 and thus also in Ada 2005: 27298 27299@table @emph 27300@item Character literals 27301Some uses of character literals are ambiguous. Since Ada 95 has introduced 27302@code{Wide_Character} as a new predefined character type, some uses of 27303character literals that were legal in Ada 83 are illegal in Ada 95. 27304For example: 27305@smallexample @c ada 27306 for Char in 'A' .. 'Z' loop @dots{} end loop; 27307@end smallexample 27308 27309@noindent 27310The problem is that @code{'A'} and @code{'Z'} could be from either 27311@code{Character} or @code{Wide_Character}. The simplest correction 27312is to make the type explicit; e.g.: 27313@smallexample @c ada 27314 for Char in Character range 'A' .. 'Z' loop @dots{} end loop; 27315@end smallexample 27316 27317@item New reserved words 27318The identifiers @code{abstract}, @code{aliased}, @code{protected}, 27319@code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95. 27320Existing Ada 83 code using any of these identifiers must be edited to 27321use some alternative name. 27322 27323@item Freezing rules 27324The rules in Ada 95 are slightly different with regard to the point at 27325which entities are frozen, and representation pragmas and clauses are 27326not permitted past the freeze point. This shows up most typically in 27327the form of an error message complaining that a representation item 27328appears too late, and the appropriate corrective action is to move 27329the item nearer to the declaration of the entity to which it refers. 27330 27331A particular case is that representation pragmas 27332@ifset vms 27333(including the 27334extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure}) 27335@end ifset 27336cannot be applied to a subprogram body. If necessary, a separate subprogram 27337declaration must be introduced to which the pragma can be applied. 27338 27339@item Optional bodies for library packages 27340In Ada 83, a package that did not require a package body was nevertheless 27341allowed to have one. This lead to certain surprises in compiling large 27342systems (situations in which the body could be unexpectedly ignored by the 27343binder). In Ada 95, if a package does not require a body then it is not 27344permitted to have a body. To fix this problem, simply remove a redundant 27345body if it is empty, or, if it is non-empty, introduce a dummy declaration 27346into the spec that makes the body required. One approach is to add a private 27347part to the package declaration (if necessary), and define a parameterless 27348procedure called @code{Requires_Body}, which must then be given a dummy 27349procedure body in the package body, which then becomes required. 27350Another approach (assuming that this does not introduce elaboration 27351circularities) is to add an @code{Elaborate_Body} pragma to the package spec, 27352since one effect of this pragma is to require the presence of a package body. 27353 27354@item @code{Numeric_Error} is now the same as @code{Constraint_Error} 27355In Ada 95, the exception @code{Numeric_Error} is a renaming of 27356@code{Constraint_Error}. 27357This means that it is illegal to have separate exception handlers for 27358the two exceptions. The fix is simply to remove the handler for the 27359@code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise 27360@code{Constraint_Error} in place of @code{Numeric_Error} in all cases). 27361 27362@item Indefinite subtypes in generics 27363In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String}) 27364as the actual for a generic formal private type, but then the instantiation 27365would be illegal if there were any instances of declarations of variables 27366of this type in the generic body. In Ada 95, to avoid this clear violation 27367of the methodological principle known as the ``contract model'', 27368the generic declaration explicitly indicates whether 27369or not such instantiations are permitted. If a generic formal parameter 27370has explicit unknown discriminants, indicated by using @code{(<>)} after the 27371subtype name, then it can be instantiated with indefinite types, but no 27372stand-alone variables can be declared of this type. Any attempt to declare 27373such a variable will result in an illegality at the time the generic is 27374declared. If the @code{(<>)} notation is not used, then it is illegal 27375to instantiate the generic with an indefinite type. 27376This is the potential incompatibility issue when porting Ada 83 code to Ada 95. 27377It will show up as a compile time error, and 27378the fix is usually simply to add the @code{(<>)} to the generic declaration. 27379@end table 27380 27381@node More deterministic semantics 27382@subsection More deterministic semantics 27383 27384@table @emph 27385@item Conversions 27386Conversions from real types to integer types round away from 0. In Ada 83 27387the conversion Integer(2.5) could deliver either 2 or 3 as its value. This 27388implementation freedom was intended to support unbiased rounding in 27389statistical applications, but in practice it interfered with portability. 27390In Ada 95 the conversion semantics are unambiguous, and rounding away from 0 27391is required. Numeric code may be affected by this change in semantics. 27392Note, though, that this issue is no worse than already existed in Ada 83 27393when porting code from one vendor to another. 27394 27395@item Tasking 27396The Real-Time Annex introduces a set of policies that define the behavior of 27397features that were implementation dependent in Ada 83, such as the order in 27398which open select branches are executed. 27399@end table 27400 27401@node Changed semantics 27402@subsection Changed semantics 27403 27404@noindent 27405The worst kind of incompatibility is one where a program that is legal in 27406Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not 27407possible in Ada 83. Fortunately this is extremely rare, but the one 27408situation that you should be alert to is the change in the predefined type 27409@code{Character} from 7-bit ASCII to 8-bit Latin-1. 27410 27411@table @emph 27412@item Range of type @code{Character} 27413The range of @code{Standard.Character} is now the full 256 characters 27414of Latin-1, whereas in most Ada 83 implementations it was restricted 27415to 128 characters. Although some of the effects of 27416this change will be manifest in compile-time rejection of legal 27417Ada 83 programs it is possible for a working Ada 83 program to have 27418a different effect in Ada 95, one that was not permitted in Ada 83. 27419As an example, the expression 27420@code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now 27421delivers @code{255} as its value. 27422In general, you should look at the logic of any 27423character-processing Ada 83 program and see whether it needs to be adapted 27424to work correctly with Latin-1. Note that the predefined Ada 95 API has a 27425character handling package that may be relevant if code needs to be adapted 27426to account for the additional Latin-1 elements. 27427The desirable fix is to 27428modify the program to accommodate the full character set, but in some cases 27429it may be convenient to define a subtype or derived type of Character that 27430covers only the restricted range. 27431@cindex Latin-1 27432@end table 27433 27434@node Other language compatibility issues 27435@subsection Other language compatibility issues 27436 27437@table @emph 27438@item @option{-gnat83} switch 27439All implementations of GNAT provide a switch that causes GNAT to operate 27440in Ada 83 mode. In this mode, some but not all compatibility problems 27441of the type described above are handled automatically. For example, the 27442new reserved words introduced in Ada 95 and Ada 2005 are treated simply 27443as identifiers as in Ada 83. 27444However, 27445in practice, it is usually advisable to make the necessary modifications 27446to the program to remove the need for using this switch. 27447See @ref{Compiling Different Versions of Ada}. 27448 27449@item Support for removed Ada 83 pragmas and attributes 27450A number of pragmas and attributes from Ada 83 were removed from Ada 95, 27451generally because they were replaced by other mechanisms. Ada 95 and Ada 2005 27452compilers are allowed, but not required, to implement these missing 27453elements. In contrast with some other compilers, GNAT implements all 27454such pragmas and attributes, eliminating this compatibility concern. These 27455include @code{pragma Interface} and the floating point type attributes 27456(@code{Emax}, @code{Mantissa}, etc.), among other items. 27457@end table 27458 27459 27460@node Compatibility between Ada 95 and Ada 2005 27461@section Compatibility between Ada 95 and Ada 2005 27462@cindex Compatibility between Ada 95 and Ada 2005 27463 27464@noindent 27465Although Ada 2005 was designed to be upwards compatible with Ada 95, there are 27466a number of incompatibilities. Several are enumerated below; 27467for a complete description please see the 27468Annotated Ada 2005 Reference Manual, or section 9.1.1 in 27469@cite{Rationale for Ada 2005}. 27470 27471@table @emph 27472@item New reserved words. 27473The words @code{interface}, @code{overriding} and @code{synchronized} are 27474reserved in Ada 2005. 27475A pre-Ada 2005 program that uses any of these as an identifier will be 27476illegal. 27477 27478@item New declarations in predefined packages. 27479A number of packages in the predefined environment contain new declarations: 27480@code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings}, 27481@code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded}, 27482@code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed}, 27483@code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded}, 27484@code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}. 27485If an Ada 95 program does a @code{with} and @code{use} of any of these 27486packages, the new declarations may cause name clashes. 27487 27488@item Access parameters. 27489A nondispatching subprogram with an access parameter cannot be renamed 27490as a dispatching operation. This was permitted in Ada 95. 27491 27492@item Access types, discriminants, and constraints. 27493Rule changes in this area have led to some incompatibilities; for example, 27494constrained subtypes of some access types are not permitted in Ada 2005. 27495 27496@item Aggregates for limited types. 27497The allowance of aggregates for limited types in Ada 2005 raises the 27498possibility of ambiguities in legal Ada 95 programs, since additional types 27499now need to be considered in expression resolution. 27500 27501@item Fixed-point multiplication and division. 27502Certain expressions involving ``*'' or ``/'' for a fixed-point type, which 27503were legal in Ada 95 and invoked the predefined versions of these operations, 27504are now ambiguous. 27505The ambiguity may be resolved either by applying a type conversion to the 27506expression, or by explicitly invoking the operation from package 27507@code{Standard}. 27508 27509@item Return-by-reference types. 27510The Ada 95 return-by-reference mechanism has been removed. Instead, the user 27511can declare a function returning a value from an anonymous access type. 27512@end table 27513 27514 27515@node Implementation-dependent characteristics 27516@section Implementation-dependent characteristics 27517@noindent 27518Although the Ada language defines the semantics of each construct as 27519precisely as practical, in some situations (for example for reasons of 27520efficiency, or where the effect is heavily dependent on the host or target 27521platform) the implementation is allowed some freedom. In porting Ada 83 27522code to GNAT, you need to be aware of whether / how the existing code 27523exercised such implementation dependencies. Such characteristics fall into 27524several categories, and GNAT offers specific support in assisting the 27525transition from certain Ada 83 compilers. 27526 27527@menu 27528* Implementation-defined pragmas:: 27529* Implementation-defined attributes:: 27530* Libraries:: 27531* Elaboration order:: 27532* Target-specific aspects:: 27533@end menu 27534 27535@node Implementation-defined pragmas 27536@subsection Implementation-defined pragmas 27537 27538@noindent 27539Ada compilers are allowed to supplement the language-defined pragmas, and 27540these are a potential source of non-portability. All GNAT-defined pragmas 27541are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT 27542Reference Manual}, and these include several that are specifically 27543intended to correspond to other vendors' Ada 83 pragmas. 27544For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful. 27545For compatibility with HP Ada 83, GNAT supplies the pragmas 27546@code{Extend_System}, @code{Ident}, @code{Inline_Generic}, 27547@code{Interface_Name}, @code{Passive}, @code{Suppress_All}, 27548and @code{Volatile}. 27549Other relevant pragmas include @code{External} and @code{Link_With}. 27550Some vendor-specific 27551Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are 27552recognized, thus 27553avoiding compiler rejection of units that contain such pragmas; they are not 27554relevant in a GNAT context and hence are not otherwise implemented. 27555 27556@node Implementation-defined attributes 27557@subsection Implementation-defined attributes 27558 27559Analogous to pragmas, the set of attributes may be extended by an 27560implementation. All GNAT-defined attributes are described in 27561@ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference 27562Manual}, and these include several that are specifically intended 27563to correspond to other vendors' Ada 83 attributes. For migrating from VADS, 27564the attribute @code{VADS_Size} may be useful. For compatibility with HP 27565Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and 27566@code{Type_Class}. 27567 27568@node Libraries 27569@subsection Libraries 27570@noindent 27571Vendors may supply libraries to supplement the standard Ada API. If Ada 83 27572code uses vendor-specific libraries then there are several ways to manage 27573this in Ada 95 or Ada 2005: 27574@enumerate 27575@item 27576If the source code for the libraries (specs and bodies) are 27577available, then the libraries can be migrated in the same way as the 27578application. 27579@item 27580If the source code for the specs but not the bodies are 27581available, then you can reimplement the bodies. 27582@item 27583Some features introduced by Ada 95 obviate the need for library support. For 27584example most Ada 83 vendors supplied a package for unsigned integers. The 27585Ada 95 modular type feature is the preferred way to handle this need, so 27586instead of migrating or reimplementing the unsigned integer package it may 27587be preferable to retrofit the application using modular types. 27588@end enumerate 27589 27590@node Elaboration order 27591@subsection Elaboration order 27592@noindent 27593The implementation can choose any elaboration order consistent with the unit 27594dependency relationship. This freedom means that some orders can result in 27595Program_Error being raised due to an ``Access Before Elaboration'': an attempt 27596to invoke a subprogram its body has been elaborated, or to instantiate a 27597generic before the generic body has been elaborated. By default GNAT 27598attempts to choose a safe order (one that will not encounter access before 27599elaboration problems) by implicitly inserting @code{Elaborate} or 27600@code{Elaborate_All} pragmas where 27601needed. However, this can lead to the creation of elaboration circularities 27602and a resulting rejection of the program by gnatbind. This issue is 27603thoroughly described in @ref{Elaboration Order Handling in GNAT}. 27604In brief, there are several 27605ways to deal with this situation: 27606 27607@itemize @bullet 27608@item 27609Modify the program to eliminate the circularities, e.g.@: by moving 27610elaboration-time code into explicitly-invoked procedures 27611@item 27612Constrain the elaboration order by including explicit @code{Elaborate_Body} or 27613@code{Elaborate} pragmas, and then inhibit the generation of implicit 27614@code{Elaborate_All} 27615pragmas either globally (as an effect of the @option{-gnatE} switch) or locally 27616(by selectively suppressing elaboration checks via pragma 27617@code{Suppress(Elaboration_Check)} when it is safe to do so). 27618@end itemize 27619 27620@node Target-specific aspects 27621@subsection Target-specific aspects 27622@noindent 27623Low-level applications need to deal with machine addresses, data 27624representations, interfacing with assembler code, and similar issues. If 27625such an Ada 83 application is being ported to different target hardware (for 27626example where the byte endianness has changed) then you will need to 27627carefully examine the program logic; the porting effort will heavily depend 27628on the robustness of the original design. Moreover, Ada 95 (and thus 27629Ada 2005) are sometimes 27630incompatible with typical Ada 83 compiler practices regarding implicit 27631packing, the meaning of the Size attribute, and the size of access values. 27632GNAT's approach to these issues is described in @ref{Representation Clauses}. 27633 27634@node Compatibility with Other Ada Systems 27635@section Compatibility with Other Ada Systems 27636 27637@noindent 27638If programs avoid the use of implementation dependent and 27639implementation defined features, as documented in the @cite{Ada 27640Reference Manual}, there should be a high degree of portability between 27641GNAT and other Ada systems. The following are specific items which 27642have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95 27643compilers, but do not affect porting code to GNAT@. 27644(As of @value{NOW}, GNAT is the only compiler available for Ada 2005; 27645the following issues may or may not arise for Ada 2005 programs 27646when other compilers appear.) 27647 27648@table @emph 27649@item Ada 83 Pragmas and Attributes 27650Ada 95 compilers are allowed, but not required, to implement the missing 27651Ada 83 pragmas and attributes that are no longer defined in Ada 95. 27652GNAT implements all such pragmas and attributes, eliminating this as 27653a compatibility concern, but some other Ada 95 compilers reject these 27654pragmas and attributes. 27655 27656@item Specialized Needs Annexes 27657GNAT implements the full set of special needs annexes. At the 27658current time, it is the only Ada 95 compiler to do so. This means that 27659programs making use of these features may not be portable to other Ada 2766095 compilation systems. 27661 27662@item Representation Clauses 27663Some other Ada 95 compilers implement only the minimal set of 27664representation clauses required by the Ada 95 reference manual. GNAT goes 27665far beyond this minimal set, as described in the next section. 27666@end table 27667 27668@node Representation Clauses 27669@section Representation Clauses 27670 27671@noindent 27672The Ada 83 reference manual was quite vague in describing both the minimal 27673required implementation of representation clauses, and also their precise 27674effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the 27675minimal set of capabilities required is still quite limited. 27676 27677GNAT implements the full required set of capabilities in 27678Ada 95 and Ada 2005, but also goes much further, and in particular 27679an effort has been made to be compatible with existing Ada 83 usage to the 27680greatest extent possible. 27681 27682A few cases exist in which Ada 83 compiler behavior is incompatible with 27683the requirements in Ada 95 (and thus also Ada 2005). These are instances of 27684intentional or accidental dependence on specific implementation dependent 27685characteristics of these Ada 83 compilers. The following is a list of 27686the cases most likely to arise in existing Ada 83 code. 27687 27688@table @emph 27689@item Implicit Packing 27690Some Ada 83 compilers allowed a Size specification to cause implicit 27691packing of an array or record. This could cause expensive implicit 27692conversions for change of representation in the presence of derived 27693types, and the Ada design intends to avoid this possibility. 27694Subsequent AI's were issued to make it clear that such implicit 27695change of representation in response to a Size clause is inadvisable, 27696and this recommendation is represented explicitly in the Ada 95 (and Ada 2005) 27697Reference Manuals as implementation advice that is followed by GNAT@. 27698The problem will show up as an error 27699message rejecting the size clause. The fix is simply to provide 27700the explicit pragma @code{Pack}, or for more fine tuned control, provide 27701a Component_Size clause. 27702 27703@item Meaning of Size Attribute 27704The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as 27705the minimal number of bits required to hold values of the type. For example, 27706on a 32-bit machine, the size of @code{Natural} will typically be 31 and not 2770732 (since no sign bit is required). Some Ada 83 compilers gave 31, and 27708some 32 in this situation. This problem will usually show up as a compile 27709time error, but not always. It is a good idea to check all uses of the 27710'Size attribute when porting Ada 83 code. The GNAT specific attribute 27711Object_Size can provide a useful way of duplicating the behavior of 27712some Ada 83 compiler systems. 27713 27714@item Size of Access Types 27715A common assumption in Ada 83 code is that an access type is in fact a pointer, 27716and that therefore it will be the same size as a System.Address value. This 27717assumption is true for GNAT in most cases with one exception. For the case of 27718a pointer to an unconstrained array type (where the bounds may vary from one 27719value of the access type to another), the default is to use a ``fat pointer'', 27720which is represented as two separate pointers, one to the bounds, and one to 27721the array. This representation has a number of advantages, including improved 27722efficiency. However, it may cause some difficulties in porting existing Ada 83 27723code which makes the assumption that, for example, pointers fit in 32 bits on 27724a machine with 32-bit addressing. 27725 27726To get around this problem, GNAT also permits the use of ``thin pointers'' for 27727access types in this case (where the designated type is an unconstrained array 27728type). These thin pointers are indeed the same size as a System.Address value. 27729To specify a thin pointer, use a size clause for the type, for example: 27730 27731@smallexample @c ada 27732type X is access all String; 27733for X'Size use Standard'Address_Size; 27734@end smallexample 27735 27736@noindent 27737which will cause the type X to be represented using a single pointer. 27738When using this representation, the bounds are right behind the array. 27739This representation is slightly less efficient, and does not allow quite 27740such flexibility in the use of foreign pointers or in using the 27741Unrestricted_Access attribute to create pointers to non-aliased objects. 27742But for any standard portable use of the access type it will work in 27743a functionally correct manner and allow porting of existing code. 27744Note that another way of forcing a thin pointer representation 27745is to use a component size clause for the element size in an array, 27746or a record representation clause for an access field in a record. 27747@end table 27748 27749@ifclear vms 27750@c This brief section is only in the non-VMS version 27751@c The complete chapter on HP Ada is in the VMS version 27752@node Compatibility with HP Ada 83 27753@section Compatibility with HP Ada 83 27754 27755@noindent 27756The VMS version of GNAT fully implements all the pragmas and attributes 27757provided by HP Ada 83, as well as providing the standard HP Ada 83 27758libraries, including Starlet. In addition, data layouts and parameter 27759passing conventions are highly compatible. This means that porting 27760existing HP Ada 83 code to GNAT in VMS systems should be easier than 27761most other porting efforts. The following are some of the most 27762significant differences between GNAT and HP Ada 83. 27763 27764@table @emph 27765@item Default floating-point representation 27766In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83, 27767it is VMS format. GNAT does implement the necessary pragmas 27768(Long_Float, Float_Representation) for changing this default. 27769 27770@item System 27771The package System in GNAT exactly corresponds to the definition in the 27772Ada 95 reference manual, which means that it excludes many of the 27773HP Ada 83 extensions. However, a separate package Aux_DEC is provided 27774that contains the additional definitions, and a special pragma, 27775Extend_System allows this package to be treated transparently as an 27776extension of package System. 27777 27778@item To_Address 27779The definitions provided by Aux_DEC are exactly compatible with those 27780in the HP Ada 83 version of System, with one exception. 27781HP Ada provides the following declarations: 27782 27783@smallexample @c ada 27784TO_ADDRESS (INTEGER) 27785TO_ADDRESS (UNSIGNED_LONGWORD) 27786TO_ADDRESS (@i{universal_integer}) 27787@end smallexample 27788 27789@noindent 27790The version of TO_ADDRESS taking a @i{universal integer} argument is in fact 27791an extension to Ada 83 not strictly compatible with the reference manual. 27792In GNAT, we are constrained to be exactly compatible with the standard, 27793and this means we cannot provide this capability. In HP Ada 83, the 27794point of this definition is to deal with a call like: 27795 27796@smallexample @c ada 27797TO_ADDRESS (16#12777#); 27798@end smallexample 27799 27800@noindent 27801Normally, according to the Ada 83 standard, one would expect this to be 27802ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms 27803of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the 27804definition using @i{universal_integer} takes precedence. 27805 27806In GNAT, since the version with @i{universal_integer} cannot be supplied, it 27807is not possible to be 100% compatible. Since there are many programs using 27808numeric constants for the argument to TO_ADDRESS, the decision in GNAT was 27809to change the name of the function in the UNSIGNED_LONGWORD case, so the 27810declarations provided in the GNAT version of AUX_Dec are: 27811 27812@smallexample @c ada 27813function To_Address (X : Integer) return Address; 27814pragma Pure_Function (To_Address); 27815 27816function To_Address_Long (X : Unsigned_Longword) 27817 return Address; 27818pragma Pure_Function (To_Address_Long); 27819@end smallexample 27820 27821@noindent 27822This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must 27823change the name to TO_ADDRESS_LONG@. 27824 27825@item Task_Id values 27826The Task_Id values assigned will be different in the two systems, and GNAT 27827does not provide a specified value for the Task_Id of the environment task, 27828which in GNAT is treated like any other declared task. 27829@end table 27830 27831@noindent 27832For full details on these and other less significant compatibility issues, 27833see appendix E of the HP publication entitled @cite{HP Ada, Technical 27834Overview and Comparison on HP Platforms}. 27835 27836For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and 27837attributes are recognized, although only a subset of them can sensibly 27838be implemented. The description of pragmas in @ref{Implementation 27839Defined Pragmas,,, gnat_rm, GNAT Reference Manual} 27840indicates whether or not they are applicable to non-VMS systems. 27841@end ifclear 27842 27843@ifset vms 27844@node Transitioning to 64-Bit GNAT for OpenVMS 27845@section Transitioning to 64-Bit @value{EDITION} for OpenVMS 27846 27847@noindent 27848This section is meant to assist users of pre-2006 @value{EDITION} 27849for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION}, 27850the version of the GNAT technology supplied in 2006 and later for 27851OpenVMS on both Alpha and I64. 27852 27853@menu 27854* Introduction to transitioning:: 27855* Migration of 32 bit code:: 27856* Taking advantage of 64 bit addressing:: 27857* Technical details:: 27858@end menu 27859 27860@node Introduction to transitioning 27861@subsection Introduction 27862 27863@noindent 2786464-bit @value{EDITION} for Open VMS has been designed to meet 27865three main goals: 27866 27867@enumerate 27868@item 27869Providing a full conforming implementation of Ada 95 and Ada 2005 27870 27871@item 27872Allowing maximum backward compatibility, thus easing migration of existing 27873Ada source code 27874 27875@item 27876Supplying a path for exploiting the full 64-bit address range 27877@end enumerate 27878 27879@noindent 27880Ada's strong typing semantics has made it 27881impractical to have different 32-bit and 64-bit modes. As soon as 27882one object could possibly be outside the 32-bit address space, this 27883would make it necessary for the @code{System.Address} type to be 64 bits. 27884In particular, this would cause inconsistencies if 32-bit code is 27885called from 64-bit code that raises an exception. 27886 27887This issue has been resolved by always using 64-bit addressing 27888at the system level, but allowing for automatic conversions between 2788932-bit and 64-bit addresses where required. Thus users who 27890do not currently require 64-bit addressing capabilities, can 27891recompile their code with only minimal changes (and indeed 27892if the code is written in portable Ada, with no assumptions about 27893the size of the @code{Address} type, then no changes at all are necessary). 27894At the same time, 27895this approach provides a simple, gradual upgrade path to future 27896use of larger memories than available for 32-bit systems. 27897Also, newly written applications or libraries will by default 27898be fully compatible with future systems exploiting 64-bit 27899addressing capabilities. 27900 27901@ref{Migration of 32 bit code}, will focus on porting applications 27902that do not require more than 2 GB of 27903addressable memory. This code will be referred to as 27904@emph{32-bit code}. 27905For applications intending to exploit the full 64-bit address space, 27906@ref{Taking advantage of 64 bit addressing}, 27907will consider further changes that may be required. 27908Such code will be referred to below as @emph{64-bit code}. 27909 27910@node Migration of 32 bit code 27911@subsection Migration of 32-bit code 27912 27913@menu 27914* Address types:: 27915* Access types and 32/64-bit allocation:: 27916* Unchecked conversions:: 27917* Predefined constants:: 27918* Interfacing with C:: 27919* 32/64-bit descriptors:: 27920* Experience with source compatibility:: 27921@end menu 27922 27923@node Address types 27924@subsubsection Address types 27925 27926@noindent 27927To solve the problem of mixing 64-bit and 32-bit addressing, 27928while maintaining maximum backward compatibility, the following 27929approach has been taken: 27930 27931@itemize @bullet 27932@item 27933@code{System.Address} always has a size of 64 bits 27934@cindex @code{System.Address} size 27935@cindex @code{Address} size 27936 27937@item 27938@code{System.Short_Address} is a 32-bit subtype of @code{System.Address} 27939@cindex @code{System.Short_Address} size 27940@cindex @code{Short_Address} size 27941@end itemize 27942 27943@noindent 27944Since @code{System.Short_Address} is a subtype of @code{System.Address}, 27945a @code{Short_Address} 27946may be used where an @code{Address} is required, and vice versa, without 27947needing explicit type conversions. 27948By virtue of the Open VMS parameter passing conventions, 27949even imported 27950and exported subprograms that have 32-bit address parameters are 27951compatible with those that have 64-bit address parameters. 27952(See @ref{Making code 64 bit clean} for details.) 27953 27954The areas that may need attention are those where record types have 27955been defined that contain components of the type @code{System.Address}, and 27956where objects of this type are passed to code expecting a record layout with 2795732-bit addresses. 27958 27959Different compilers on different platforms cannot be 27960expected to represent the same type in the same way, 27961since alignment constraints 27962and other system-dependent properties affect the compiler's decision. 27963For that reason, Ada code 27964generally uses representation clauses to specify the expected 27965layout where required. 27966 27967If such a representation clause uses 32 bits for a component having 27968the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS 27969will detect that error and produce a specific diagnostic message. 27970The developer should then determine whether the representation 27971should be 64 bits or not and make either of two changes: 27972change the size to 64 bits and leave the type as @code{System.Address}, or 27973leave the size as 32 bits and change the type to @code{System.Short_Address}. 27974Since @code{Short_Address} is a subtype of @code{Address}, no changes are 27975required in any code setting or accessing the field; the compiler will 27976automatically perform any needed conversions between address 27977formats. 27978 27979@node Access types and 32/64-bit allocation 27980@subsubsection Access types and 32/64-bit allocation 27981@cindex 32-bit allocation 27982@cindex 64-bit allocation 27983 27984@noindent 27985By default, objects designated by access values are always allocated in 27986the 64-bit address space, and access values themselves are represented 27987in 64 bits. If these defaults are not appropriate, and 32-bit allocation 27988is required (for example if the address of an allocated object is assigned 27989to a @code{Short_Address} variable), then several alternatives are available: 27990 27991@itemize @bullet 27992@item 27993A pool-specific access type (ie, an @w{Ada 83} access type, whose 27994definition is @code{access T} versus @code{access all T} or 27995@code{access constant T}), may be declared with a @code{'Size} representation 27996clause that establishes the size as 32 bits. 27997In such circumstances allocations for that type will 27998be from the 32-bit heap. Such a clause is not permitted 27999for a general access type (declared with @code{access all} or 28000@code{access constant}) as values of such types must be able to refer 28001to any object of the designated type, including objects residing outside 28002the 32-bit address range. Existing @w{Ada 83} code will not contain such 28003type definitions, however, since general access types were introduced 28004in @w{Ada 95}. 28005 28006@item 28007Switches for @command{GNAT BIND} control whether the internal GNAT 28008allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations. 28009@cindex @code{__gnat_malloc} 28010The switches are respectively @option{-H64} (the default) and 28011@option{-H32}. 28012@cindex @option{-H32} (@command{gnatbind}) 28013@cindex @option{-H64} (@command{gnatbind}) 28014 28015@item 28016The environment variable (logical name) @code{GNAT$NO_MALLOC_64} 28017@cindex @code{GNAT$NO_MALLOC_64} environment variable 28018may be used to force @code{__gnat_malloc} to use 32-bit allocation. 28019If this variable is left 28020undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"}, 28021then the default (64-bit) allocation is used. 28022If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"}, 28023then 32-bit allocation is used. The gnatbind qualifiers described above 28024override this logical name. 28025 28026@item 28027A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates 28028@cindex @option{-mno-malloc64} (^gcc^gcc^) 28029at a low level to convert explicit calls to @code{malloc} and related 28030functions from the C run-time library so that they perform allocations 28031in the 32-bit heap. 28032Since all internal allocations from GNAT use @code{__gnat_malloc}, 28033this switch is not required unless the program makes explicit calls on 28034@code{malloc} (or related functions) from interfaced C code. 28035@end itemize 28036 28037 28038@node Unchecked conversions 28039@subsubsection Unchecked conversions 28040 28041@noindent 28042In the case of an @code{Unchecked_Conversion} where the source type is a 2804364-bit access type or the type @code{System.Address}, and the target 28044type is a 32-bit type, the compiler will generate a warning. 28045Even though the generated code will still perform the required 28046conversions, it is highly recommended in these cases to use 28047respectively a 32-bit access type or @code{System.Short_Address} 28048as the source type. 28049 28050@node Predefined constants 28051@subsubsection Predefined constants 28052 28053@noindent 28054The following table shows the correspondence between pre-2006 versions of 28055@value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION} 28056(``New''): 28057 28058@multitable {@code{System.Short_Memory_Size}} {2**32} {2**64} 28059@item @b{Constant} @tab @b{Old} @tab @b{New} 28060@item @code{System.Word_Size} @tab 32 @tab 64 28061@item @code{System.Memory_Size} @tab 2**32 @tab 2**64 28062@item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32 28063@item @code{System.Address_Size} @tab 32 @tab 64 28064@end multitable 28065 28066@noindent 28067If you need to refer to the specific 28068memory size of a 32-bit implementation, instead of the 28069actual memory size, use @code{System.Short_Memory_Size} 28070rather than @code{System.Memory_Size}. 28071Similarly, references to @code{System.Address_Size} may need 28072to be replaced by @code{System.Short_Address'Size}. 28073The program @command{gnatfind} may be useful for locating 28074references to the above constants, so that you can verify that they 28075are still correct. 28076 28077@node Interfacing with C 28078@subsubsection Interfacing with C 28079 28080@noindent 28081In order to minimize the impact of the transition to 64-bit addresses on 28082legacy programs, some fundamental types in the @code{Interfaces.C} 28083package hierarchy continue to be represented in 32 bits. 28084These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}. 28085This eases integration with the default HP C layout choices, for example 28086as found in the system routines in @code{DECC$SHR.EXE}. 28087Because of this implementation choice, the type fully compatible with 28088@code{chars_ptr} is now @code{Short_Address} and not @code{Address}. 28089Depending on the context the compiler will issue a 28090warning or an error when type @code{Address} is used, alerting the user to a 28091potential problem. Otherwise 32-bit programs that use 28092@code{Interfaces.C} should normally not require code modifications 28093 28094The other issue arising with C interfacing concerns pragma @code{Convention}. 28095For VMS 64-bit systems, there is an issue of the appropriate default size 28096of C convention pointers in the absence of an explicit size clause. The HP 28097C compiler can choose either 32 or 64 bits depending on compiler options. 28098GNAT chooses 32-bits rather than 64-bits in the default case where no size 28099clause is given. This proves a better choice for porting 32-bit legacy 28100applications. In order to have a 64-bit representation, it is necessary to 28101specify a size representation clause. For example: 28102 28103@smallexample @c ada 28104type int_star is access Interfaces.C.int; 28105pragma Convention(C, int_star); 28106for int_star'Size use 64; -- Necessary to get 64 and not 32 bits 28107@end smallexample 28108 28109@node 32/64-bit descriptors 28110@subsubsection 32/64-bit descriptors 28111 28112@noindent 28113By default, GNAT uses a 64-bit descriptor mechanism. For an imported 28114subprogram (i.e., a subprogram identified by pragma @code{Import_Function}, 28115@code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies 28116@code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used. 28117@cindex @code{Short_Descriptor} mechanism for imported subprograms 28118 28119If the configuration pragma @code{Short_Descriptors} is supplied, then 28120all descriptors will be 32 bits. 28121@cindex pragma @code{Short_Descriptors} 28122 28123@node Experience with source compatibility 28124@subsubsection Experience with source compatibility 28125 28126@noindent 28127The Security Server and STARLET on I64 provide an interesting ``test case'' 28128for source compatibility issues, since it is in such system code 28129where assumptions about @code{Address} size might be expected to occur. 28130Indeed, there were a small number of occasions in the Security Server 28131file @file{jibdef.ads} 28132where a representation clause for a record type specified 2813332 bits for a component of type @code{Address}. 28134All of these errors were detected by the compiler. 28135The repair was obvious and immediate; to simply replace @code{Address} by 28136@code{Short_Address}. 28137 28138In the case of STARLET, there were several record types that should 28139have had representation clauses but did not. In these record types 28140there was an implicit assumption that an @code{Address} value occupied 2814132 bits. 28142These compiled without error, but their usage resulted in run-time error 28143returns from STARLET system calls. 28144Future GNAT technology enhancements may include a tool that detects and flags 28145these sorts of potential source code porting problems. 28146 28147@c **************************************** 28148@node Taking advantage of 64 bit addressing 28149@subsection Taking advantage of 64-bit addressing 28150 28151@menu 28152* Making code 64 bit clean:: 28153* Allocating memory from the 64 bit storage pool:: 28154* Restrictions on use of 64 bit objects:: 28155* STARLET and other predefined libraries:: 28156@end menu 28157 28158@node Making code 64 bit clean 28159@subsubsection Making code 64-bit clean 28160 28161@noindent 28162In order to prevent problems that may occur when (parts of) a 28163system start using memory outside the 32-bit address range, 28164we recommend some additional guidelines: 28165 28166@itemize @bullet 28167@item 28168For imported subprograms that take parameters of the 28169type @code{System.Address}, ensure that these subprograms can 28170indeed handle 64-bit addresses. If not, or when in doubt, 28171change the subprogram declaration to specify 28172@code{System.Short_Address} instead. 28173 28174@item 28175Resolve all warnings related to size mismatches in 28176unchecked conversions. Failing to do so causes 28177erroneous execution if the source object is outside 28178the 32-bit address space. 28179 28180@item 28181(optional) Explicitly use the 32-bit storage pool 28182for access types used in a 32-bit context, or use 28183generic access types where possible 28184(@pxref{Restrictions on use of 64 bit objects}). 28185@end itemize 28186 28187@noindent 28188If these rules are followed, the compiler will automatically insert 28189any necessary checks to ensure that no addresses or access values 28190passed to 32-bit code ever refer to objects outside the 32-bit 28191address range. 28192Any attempt to do this will raise @code{Constraint_Error}. 28193 28194@node Allocating memory from the 64 bit storage pool 28195@subsubsection Allocating memory from the 64-bit storage pool 28196 28197@noindent 28198By default, all allocations -- for both pool-specific and general 28199access types -- use the 64-bit storage pool. To override 28200this default, for an individual access type or globally, see 28201@ref{Access types and 32/64-bit allocation}. 28202 28203@node Restrictions on use of 64 bit objects 28204@subsubsection Restrictions on use of 64-bit objects 28205 28206@noindent 28207Taking the address of an object allocated from a 64-bit storage pool, 28208and then passing this address to a subprogram expecting 28209@code{System.Short_Address}, 28210or assigning it to a variable of type @code{Short_Address}, will cause 28211@code{Constraint_Error} to be raised. In case the code is not 64-bit clean 28212(@pxref{Making code 64 bit clean}), or checks are suppressed, 28213no exception is raised and execution 28214will become erroneous. 28215 28216@node STARLET and other predefined libraries 28217@subsubsection STARLET and other predefined libraries 28218 28219@noindent 28220All code that comes as part of GNAT is 64-bit clean, but the 28221restrictions given in @ref{Restrictions on use of 64 bit objects}, 28222still apply. Look at the package 28223specs to see in which contexts objects allocated 28224in 64-bit address space are acceptable. 28225 28226@node Technical details 28227@subsection Technical details 28228 28229@noindent 2823064-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the 28231Ada standard with respect to the type of @code{System.Address}. Previous 28232versions of @value{EDITION} have defined this type as private and implemented it as a 28233modular type. 28234 28235In order to allow defining @code{System.Short_Address} as a proper subtype, 28236and to match the implicit sign extension in parameter passing, 28237in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a 28238visible (i.e., non-private) integer type. 28239Standard operations on the type, such as the binary operators ``+'', ``-'', 28240etc., that take @code{Address} operands and return an @code{Address} result, 28241have been hidden by declaring these 28242@code{abstract}, a feature introduced in Ada 95 that helps avoid the potential 28243ambiguities that would otherwise result from overloading. 28244(Note that, although @code{Address} is a visible integer type, 28245good programming practice dictates against exploiting the type's 28246integer properties such as literals, since this will compromise 28247code portability.) 28248 28249Defining @code{Address} as a visible integer type helps achieve 28250maximum compatibility for existing Ada code, 28251without sacrificing the capabilities of the 64-bit architecture. 28252@end ifset 28253 28254@c ************************************************ 28255@ifset unw 28256@node Microsoft Windows Topics 28257@appendix Microsoft Windows Topics 28258@cindex Windows NT 28259@cindex Windows 95 28260@cindex Windows 98 28261 28262@noindent 28263This chapter describes topics that are specific to the Microsoft Windows 28264platforms (NT, 2000, and XP Professional). 28265 28266@menu 28267* Using GNAT on Windows:: 28268* Using a network installation of GNAT:: 28269* CONSOLE and WINDOWS subsystems:: 28270* Temporary Files:: 28271* Mixed-Language Programming on Windows:: 28272* Windows Calling Conventions:: 28273* Introduction to Dynamic Link Libraries (DLLs):: 28274* Using DLLs with GNAT:: 28275* Building DLLs with GNAT Project files:: 28276* Building DLLs with GNAT:: 28277* Building DLLs with gnatdll:: 28278* GNAT and Windows Resources:: 28279* Debugging a DLL:: 28280* Setting Stack Size from gnatlink:: 28281* Setting Heap Size from gnatlink:: 28282@end menu 28283 28284@node Using GNAT on Windows 28285@section Using GNAT on Windows 28286 28287@noindent 28288One of the strengths of the GNAT technology is that its tool set 28289(@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the 28290@code{gdb} debugger, etc.) is used in the same way regardless of the 28291platform. 28292 28293On Windows this tool set is complemented by a number of Microsoft-specific 28294tools that have been provided to facilitate interoperability with Windows 28295when this is required. With these tools: 28296 28297@itemize @bullet 28298 28299@item 28300You can build applications using the @code{CONSOLE} or @code{WINDOWS} 28301subsystems. 28302 28303@item 28304You can use any Dynamically Linked Library (DLL) in your Ada code (both 28305relocatable and non-relocatable DLLs are supported). 28306 28307@item 28308You can build Ada DLLs for use in other applications. These applications 28309can be written in a language other than Ada (e.g., C, C++, etc). Again both 28310relocatable and non-relocatable Ada DLLs are supported. 28311 28312@item 28313You can include Windows resources in your Ada application. 28314 28315@item 28316You can use or create COM/DCOM objects. 28317@end itemize 28318 28319@noindent 28320Immediately below are listed all known general GNAT-for-Windows restrictions. 28321Other restrictions about specific features like Windows Resources and DLLs 28322are listed in separate sections below. 28323 28324@itemize @bullet 28325 28326@item 28327It is not possible to use @code{GetLastError} and @code{SetLastError} 28328when tasking, protected records, or exceptions are used. In these 28329cases, in order to implement Ada semantics, the GNAT run-time system 28330calls certain Win32 routines that set the last error variable to 0 upon 28331success. It should be possible to use @code{GetLastError} and 28332@code{SetLastError} when tasking, protected record, and exception 28333features are not used, but it is not guaranteed to work. 28334 28335@item 28336It is not possible to link against Microsoft C++ libraries except for 28337import libraries. Interfacing must be done by the mean of DLLs. 28338 28339@item 28340It is possible to link against Microsoft C libraries. Yet the preferred 28341solution is to use C/C++ compiler that comes with @value{EDITION}, since it 28342doesn't require having two different development environments and makes the 28343inter-language debugging experience smoother. 28344 28345@item 28346When the compilation environment is located on FAT32 drives, users may 28347experience recompilations of the source files that have not changed if 28348Daylight Saving Time (DST) state has changed since the last time files 28349were compiled. NTFS drives do not have this problem. 28350 28351@item 28352No components of the GNAT toolset use any entries in the Windows 28353registry. The only entries that can be created are file associations and 28354PATH settings, provided the user has chosen to create them at installation 28355time, as well as some minimal book-keeping information needed to correctly 28356uninstall or integrate different GNAT products. 28357@end itemize 28358 28359@node Using a network installation of GNAT 28360@section Using a network installation of GNAT 28361 28362@noindent 28363Make sure the system on which GNAT is installed is accessible from the 28364current machine, i.e., the install location is shared over the network. 28365Shared resources are accessed on Windows by means of UNC paths, which 28366have the format @code{\\server\sharename\path} 28367 28368In order to use such a network installation, simply add the UNC path of the 28369@file{bin} directory of your GNAT installation in front of your PATH. For 28370example, if GNAT is installed in @file{\GNAT} directory of a share location 28371called @file{c-drive} on a machine @file{LOKI}, the following command will 28372make it available: 28373 28374@code{@ @ @ path \\loki\c-drive\gnat\bin;%path%} 28375 28376Be aware that every compilation using the network installation results in the 28377transfer of large amounts of data across the network and will likely cause 28378serious performance penalty. 28379 28380@node CONSOLE and WINDOWS subsystems 28381@section CONSOLE and WINDOWS subsystems 28382@cindex CONSOLE Subsystem 28383@cindex WINDOWS Subsystem 28384@cindex -mwindows 28385 28386@noindent 28387There are two main subsystems under Windows. The @code{CONSOLE} subsystem 28388(which is the default subsystem) will always create a console when 28389launching the application. This is not something desirable when the 28390application has a Windows GUI. To get rid of this console the 28391application must be using the @code{WINDOWS} subsystem. To do so 28392the @option{-mwindows} linker option must be specified. 28393 28394@smallexample 28395$ gnatmake winprog -largs -mwindows 28396@end smallexample 28397 28398@node Temporary Files 28399@section Temporary Files 28400@cindex Temporary files 28401 28402@noindent 28403It is possible to control where temporary files gets created by setting 28404the @env{TMP} environment variable. The file will be created: 28405 28406@itemize 28407@item Under the directory pointed to by the @env{TMP} environment variable if 28408this directory exists. 28409 28410@item Under @file{c:\temp}, if the @env{TMP} environment variable is not 28411set (or not pointing to a directory) and if this directory exists. 28412 28413@item Under the current working directory otherwise. 28414@end itemize 28415 28416@noindent 28417This allows you to determine exactly where the temporary 28418file will be created. This is particularly useful in networked 28419environments where you may not have write access to some 28420directories. 28421 28422@node Mixed-Language Programming on Windows 28423@section Mixed-Language Programming on Windows 28424 28425@noindent 28426Developing pure Ada applications on Windows is no different than on 28427other GNAT-supported platforms. However, when developing or porting an 28428application that contains a mix of Ada and C/C++, the choice of your 28429Windows C/C++ development environment conditions your overall 28430interoperability strategy. 28431 28432If you use @command{gcc} or Microsoft C to compile the non-Ada part of 28433your application, there are no Windows-specific restrictions that 28434affect the overall interoperability with your Ada code. If you do want 28435to use the Microsoft tools for your C++ code, you have two choices: 28436 28437@enumerate 28438@item 28439Encapsulate your C++ code in a DLL to be linked with your Ada 28440application. In this case, use the Microsoft or whatever environment to 28441build the DLL and use GNAT to build your executable 28442(@pxref{Using DLLs with GNAT}). 28443 28444@item 28445Or you can encapsulate your Ada code in a DLL to be linked with the 28446other part of your application. In this case, use GNAT to build the DLL 28447(@pxref{Building DLLs with GNAT Project files}) and use the Microsoft 28448or whatever environment to build your executable. 28449@end enumerate 28450 28451In addition to the description about C main in 28452@pxref{Mixed Language Programming} section, if the C main uses a 28453stand-alone library it is required on x86-windows to 28454setup the SEH context. For this the C main must looks like this: 28455 28456@smallexample 28457/* main.c */ 28458extern void adainit (void); 28459extern void adafinal (void); 28460extern void __gnat_initialize(void*); 28461extern void call_to_ada (void); 28462 28463int main (int argc, char *argv[]) 28464@{ 28465 int SEH [2]; 28466 28467 /* Initialize the SEH context */ 28468 __gnat_initialize (&SEH); 28469 28470 adainit(); 28471 28472 /* Then call Ada services in the stand-alone library */ 28473 28474 call_to_ada(); 28475 28476 adafinal(); 28477@} 28478@end smallexample 28479 28480Note that this is not needed on x86_64-windows where the Windows 28481native SEH support is used. 28482 28483@node Windows Calling Conventions 28484@section Windows Calling Conventions 28485@findex Stdcall 28486@findex APIENTRY 28487 28488This section pertain only to Win32. On Win64 there is a single native 28489calling convention. All convention specifiers are ignored on this 28490platform. 28491 28492@menu 28493* C Calling Convention:: 28494* Stdcall Calling Convention:: 28495* Win32 Calling Convention:: 28496* DLL Calling Convention:: 28497@end menu 28498 28499@noindent 28500When a subprogram @code{F} (caller) calls a subprogram @code{G} 28501(callee), there are several ways to push @code{G}'s parameters on the 28502stack and there are several possible scenarios to clean up the stack 28503upon @code{G}'s return. A calling convention is an agreed upon software 28504protocol whereby the responsibilities between the caller (@code{F}) and 28505the callee (@code{G}) are clearly defined. Several calling conventions 28506are available for Windows: 28507 28508@itemize @bullet 28509@item 28510@code{C} (Microsoft defined) 28511 28512@item 28513@code{Stdcall} (Microsoft defined) 28514 28515@item 28516@code{Win32} (GNAT specific) 28517 28518@item 28519@code{DLL} (GNAT specific) 28520@end itemize 28521 28522@node C Calling Convention 28523@subsection @code{C} Calling Convention 28524 28525@noindent 28526This is the default calling convention used when interfacing to C/C++ 28527routines compiled with either @command{gcc} or Microsoft Visual C++. 28528 28529In the @code{C} calling convention subprogram parameters are pushed on the 28530stack by the caller from right to left. The caller itself is in charge of 28531cleaning up the stack after the call. In addition, the name of a routine 28532with @code{C} calling convention is mangled by adding a leading underscore. 28533 28534The name to use on the Ada side when importing (or exporting) a routine 28535with @code{C} calling convention is the name of the routine. For 28536instance the C function: 28537 28538@smallexample 28539int get_val (long); 28540@end smallexample 28541 28542@noindent 28543should be imported from Ada as follows: 28544 28545@smallexample @c ada 28546@group 28547function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; 28548pragma Import (C, Get_Val, External_Name => "get_val"); 28549@end group 28550@end smallexample 28551 28552@noindent 28553Note that in this particular case the @code{External_Name} parameter could 28554have been omitted since, when missing, this parameter is taken to be the 28555name of the Ada entity in lower case. When the @code{Link_Name} parameter 28556is missing, as in the above example, this parameter is set to be the 28557@code{External_Name} with a leading underscore. 28558 28559When importing a variable defined in C, you should always use the @code{C} 28560calling convention unless the object containing the variable is part of a 28561DLL (in which case you should use the @code{Stdcall} calling 28562convention, @pxref{Stdcall Calling Convention}). 28563 28564@node Stdcall Calling Convention 28565@subsection @code{Stdcall} Calling Convention 28566 28567@noindent 28568This convention, which was the calling convention used for Pascal 28569programs, is used by Microsoft for all the routines in the Win32 API for 28570efficiency reasons. It must be used to import any routine for which this 28571convention was specified. 28572 28573In the @code{Stdcall} calling convention subprogram parameters are pushed 28574on the stack by the caller from right to left. The callee (and not the 28575caller) is in charge of cleaning the stack on routine exit. In addition, 28576the name of a routine with @code{Stdcall} calling convention is mangled by 28577adding a leading underscore (as for the @code{C} calling convention) and a 28578trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in 28579bytes) of the parameters passed to the routine. 28580 28581The name to use on the Ada side when importing a C routine with a 28582@code{Stdcall} calling convention is the name of the C routine. The leading 28583underscore and trailing @code{@@}@code{@var{nn}} are added automatically by 28584the compiler. For instance the Win32 function: 28585 28586@smallexample 28587@b{APIENTRY} int get_val (long); 28588@end smallexample 28589 28590@noindent 28591should be imported from Ada as follows: 28592 28593@smallexample @c ada 28594@group 28595function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; 28596pragma Import (Stdcall, Get_Val); 28597-- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4" 28598@end group 28599@end smallexample 28600 28601@noindent 28602As for the @code{C} calling convention, when the @code{External_Name} 28603parameter is missing, it is taken to be the name of the Ada entity in lower 28604case. If instead of writing the above import pragma you write: 28605 28606@smallexample @c ada 28607@group 28608function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; 28609pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val"); 28610@end group 28611@end smallexample 28612 28613@noindent 28614then the imported routine is @code{_retrieve_val@@4}. However, if instead 28615of specifying the @code{External_Name} parameter you specify the 28616@code{Link_Name} as in the following example: 28617 28618@smallexample @c ada 28619@group 28620function Get_Val (V : Interfaces.C.long) return Interfaces.C.int; 28621pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val"); 28622@end group 28623@end smallexample 28624 28625@noindent 28626then the imported routine is @code{retrieve_val}, that is, there is no 28627decoration at all. No leading underscore and no Stdcall suffix 28628@code{@@}@code{@var{nn}}. 28629 28630@noindent 28631This is especially important as in some special cases a DLL's entry 28632point name lacks a trailing @code{@@}@code{@var{nn}} while the exported 28633name generated for a call has it. 28634 28635@noindent 28636It is also possible to import variables defined in a DLL by using an 28637import pragma for a variable. As an example, if a DLL contains a 28638variable defined as: 28639 28640@smallexample 28641int my_var; 28642@end smallexample 28643 28644@noindent 28645then, to access this variable from Ada you should write: 28646 28647@smallexample @c ada 28648@group 28649My_Var : Interfaces.C.int; 28650pragma Import (Stdcall, My_Var); 28651@end group 28652@end smallexample 28653 28654@noindent 28655Note that to ease building cross-platform bindings this convention 28656will be handled as a @code{C} calling convention on non-Windows platforms. 28657 28658@node Win32 Calling Convention 28659@subsection @code{Win32} Calling Convention 28660 28661@noindent 28662This convention, which is GNAT-specific is fully equivalent to the 28663@code{Stdcall} calling convention described above. 28664 28665@node DLL Calling Convention 28666@subsection @code{DLL} Calling Convention 28667 28668@noindent 28669This convention, which is GNAT-specific is fully equivalent to the 28670@code{Stdcall} calling convention described above. 28671 28672@node Introduction to Dynamic Link Libraries (DLLs) 28673@section Introduction to Dynamic Link Libraries (DLLs) 28674@findex DLL 28675 28676@noindent 28677A Dynamically Linked Library (DLL) is a library that can be shared by 28678several applications running under Windows. A DLL can contain any number of 28679routines and variables. 28680 28681One advantage of DLLs is that you can change and enhance them without 28682forcing all the applications that depend on them to be relinked or 28683recompiled. However, you should be aware than all calls to DLL routines are 28684slower since, as you will understand below, such calls are indirect. 28685 28686To illustrate the remainder of this section, suppose that an application 28687wants to use the services of a DLL @file{API.dll}. To use the services 28688provided by @file{API.dll} you must statically link against the DLL or 28689an import library which contains a jump table with an entry for each 28690routine and variable exported by the DLL. In the Microsoft world this 28691import library is called @file{API.lib}. When using GNAT this import 28692library is called either @file{libAPI.dll.a}, @file{libapi.dll.a}, 28693@file{libAPI.a} or @file{libapi.a} (names are case insensitive). 28694 28695After you have linked your application with the DLL or the import library 28696and you run your application, here is what happens: 28697 28698@enumerate 28699@item 28700Your application is loaded into memory. 28701 28702@item 28703The DLL @file{API.dll} is mapped into the address space of your 28704application. This means that: 28705 28706@itemize @bullet 28707@item 28708The DLL will use the stack of the calling thread. 28709 28710@item 28711The DLL will use the virtual address space of the calling process. 28712 28713@item 28714The DLL will allocate memory from the virtual address space of the calling 28715process. 28716 28717@item 28718Handles (pointers) can be safely exchanged between routines in the DLL 28719routines and routines in the application using the DLL. 28720@end itemize 28721 28722@item 28723The entries in the jump table (from the import library @file{libAPI.dll.a} 28724or @file{API.lib} or automatically created when linking against a DLL) 28725which is part of your application are initialized with the addresses 28726of the routines and variables in @file{API.dll}. 28727 28728@item 28729If present in @file{API.dll}, routines @code{DllMain} or 28730@code{DllMainCRTStartup} are invoked. These routines typically contain 28731the initialization code needed for the well-being of the routines and 28732variables exported by the DLL. 28733@end enumerate 28734 28735@noindent 28736There is an additional point which is worth mentioning. In the Windows 28737world there are two kind of DLLs: relocatable and non-relocatable 28738DLLs. Non-relocatable DLLs can only be loaded at a very specific address 28739in the target application address space. If the addresses of two 28740non-relocatable DLLs overlap and these happen to be used by the same 28741application, a conflict will occur and the application will run 28742incorrectly. Hence, when possible, it is always preferable to use and 28743build relocatable DLLs. Both relocatable and non-relocatable DLLs are 28744supported by GNAT. Note that the @option{-s} linker option (see GNU Linker 28745User's Guide) removes the debugging symbols from the DLL but the DLL can 28746still be relocated. 28747 28748As a side note, an interesting difference between Microsoft DLLs and 28749Unix shared libraries, is the fact that on most Unix systems all public 28750routines are exported by default in a Unix shared library, while under 28751Windows it is possible (but not required) to list exported routines in 28752a definition file (@pxref{The Definition File}). 28753 28754@node Using DLLs with GNAT 28755@section Using DLLs with GNAT 28756 28757@menu 28758* Creating an Ada Spec for the DLL Services:: 28759* Creating an Import Library:: 28760@end menu 28761 28762@noindent 28763To use the services of a DLL, say @file{API.dll}, in your Ada application 28764you must have: 28765 28766@enumerate 28767@item 28768The Ada spec for the routines and/or variables you want to access in 28769@file{API.dll}. If not available this Ada spec must be built from the C/C++ 28770header files provided with the DLL. 28771 28772@item 28773The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously 28774mentioned an import library is a statically linked library containing the 28775import table which will be filled at load time to point to the actual 28776@file{API.dll} routines. Sometimes you don't have an import library for the 28777DLL you want to use. The following sections will explain how to build 28778one. Note that this is optional. 28779 28780@item 28781The actual DLL, @file{API.dll}. 28782@end enumerate 28783 28784@noindent 28785Once you have all the above, to compile an Ada application that uses the 28786services of @file{API.dll} and whose main subprogram is @code{My_Ada_App}, 28787you simply issue the command 28788 28789@smallexample 28790$ gnatmake my_ada_app -largs -lAPI 28791@end smallexample 28792 28793@noindent 28794The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command 28795tells the GNAT linker to look for an import library. The linker will 28796look for a library name in this specific order: 28797 28798@enumerate 28799@item @file{libAPI.dll.a} 28800@item @file{API.dll.a} 28801@item @file{libAPI.a} 28802@item @file{API.lib} 28803@item @file{libAPI.dll} 28804@item @file{API.dll} 28805@end enumerate 28806 28807The first three are the GNU style import libraries. The third is the 28808Microsoft style import libraries. The last two are the actual DLL names. 28809 28810Note that if the Ada package spec for @file{API.dll} contains the 28811following pragma 28812 28813@smallexample @c ada 28814pragma Linker_Options ("-lAPI"); 28815@end smallexample 28816 28817@noindent 28818you do not have to add @option{-largs -lAPI} at the end of the 28819@command{gnatmake} command. 28820 28821If any one of the items above is missing you will have to create it 28822yourself. The following sections explain how to do so using as an 28823example a fictitious DLL called @file{API.dll}. 28824 28825@node Creating an Ada Spec for the DLL Services 28826@subsection Creating an Ada Spec for the DLL Services 28827 28828@noindent 28829A DLL typically comes with a C/C++ header file which provides the 28830definitions of the routines and variables exported by the DLL. The Ada 28831equivalent of this header file is a package spec that contains definitions 28832for the imported entities. If the DLL you intend to use does not come with 28833an Ada spec you have to generate one such spec yourself. For example if 28834the header file of @file{API.dll} is a file @file{api.h} containing the 28835following two definitions: 28836 28837@smallexample 28838@group 28839@cartouche 28840int some_var; 28841int get (char *); 28842@end cartouche 28843@end group 28844@end smallexample 28845 28846@noindent 28847then the equivalent Ada spec could be: 28848 28849@smallexample @c ada 28850@group 28851@cartouche 28852with Interfaces.C.Strings; 28853package API is 28854 use Interfaces; 28855 28856 Some_Var : C.int; 28857 function Get (Str : C.Strings.Chars_Ptr) return C.int; 28858 28859private 28860 pragma Import (C, Get); 28861 pragma Import (DLL, Some_Var); 28862end API; 28863@end cartouche 28864@end group 28865@end smallexample 28866 28867@noindent 28868Note that a variable is 28869@strong{always imported with a DLL convention}. A function 28870can have @code{C} or @code{Stdcall} convention. 28871(@pxref{Windows Calling Conventions}). 28872 28873@node Creating an Import Library 28874@subsection Creating an Import Library 28875@cindex Import library 28876 28877@menu 28878* The Definition File:: 28879* GNAT-Style Import Library:: 28880* Microsoft-Style Import Library:: 28881@end menu 28882 28883@noindent 28884If a Microsoft-style import library @file{API.lib} or a GNAT-style 28885import library @file{libAPI.dll.a} or @file{libAPI.a} is available 28886with @file{API.dll} you can skip this section. You can also skip this 28887section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools 28888as in this case it is possible to link directly against the 28889DLL. Otherwise read on. 28890 28891@node The Definition File 28892@subsubsection The Definition File 28893@cindex Definition file 28894@findex .def 28895 28896@noindent 28897As previously mentioned, and unlike Unix systems, the list of symbols 28898that are exported from a DLL must be provided explicitly in Windows. 28899The main goal of a definition file is precisely that: list the symbols 28900exported by a DLL. A definition file (usually a file with a @code{.def} 28901suffix) has the following structure: 28902 28903@smallexample 28904@group 28905@cartouche 28906@r{[}LIBRARY @var{name}@r{]} 28907@r{[}DESCRIPTION @var{string}@r{]} 28908EXPORTS 28909 @var{symbol1} 28910 @var{symbol2} 28911 @dots{} 28912@end cartouche 28913@end group 28914@end smallexample 28915 28916@table @code 28917@item LIBRARY @var{name} 28918This section, which is optional, gives the name of the DLL. 28919 28920@item DESCRIPTION @var{string} 28921This section, which is optional, gives a description string that will be 28922embedded in the import library. 28923 28924@item EXPORTS 28925This section gives the list of exported symbols (procedures, functions or 28926variables). For instance in the case of @file{API.dll} the @code{EXPORTS} 28927section of @file{API.def} looks like: 28928 28929@smallexample 28930@group 28931@cartouche 28932EXPORTS 28933 some_var 28934 get 28935@end cartouche 28936@end group 28937@end smallexample 28938@end table 28939 28940@noindent 28941Note that you must specify the correct suffix (@code{@@}@code{@var{nn}}) 28942(@pxref{Windows Calling Conventions}) for a Stdcall 28943calling convention function in the exported symbols list. 28944 28945@noindent 28946There can actually be other sections in a definition file, but these 28947sections are not relevant to the discussion at hand. 28948 28949@node GNAT-Style Import Library 28950@subsubsection GNAT-Style Import Library 28951 28952@noindent 28953To create a static import library from @file{API.dll} with the GNAT tools 28954you should proceed as follows: 28955 28956@enumerate 28957@item 28958Create the definition file @file{API.def} (@pxref{The Definition File}). 28959For that use the @code{dll2def} tool as follows: 28960 28961@smallexample 28962$ dll2def API.dll > API.def 28963@end smallexample 28964 28965@noindent 28966@code{dll2def} is a very simple tool: it takes as input a DLL and prints 28967to standard output the list of entry points in the DLL. Note that if 28968some routines in the DLL have the @code{Stdcall} convention 28969(@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn} 28970suffix then you'll have to edit @file{api.def} to add it, and specify 28971@option{-k} to @command{gnatdll} when creating the import library. 28972 28973@noindent 28974Here are some hints to find the right @code{@@}@var{nn} suffix. 28975 28976@enumerate 28977@item 28978If you have the Microsoft import library (.lib), it is possible to get 28979the right symbols by using Microsoft @code{dumpbin} tool (see the 28980corresponding Microsoft documentation for further details). 28981 28982@smallexample 28983$ dumpbin /exports api.lib 28984@end smallexample 28985 28986@item 28987If you have a message about a missing symbol at link time the compiler 28988tells you what symbol is expected. You just have to go back to the 28989definition file and add the right suffix. 28990@end enumerate 28991 28992@item 28993Build the import library @code{libAPI.dll.a}, using @code{gnatdll} 28994(@pxref{Using gnatdll}) as follows: 28995 28996@smallexample 28997$ gnatdll -e API.def -d API.dll 28998@end smallexample 28999 29000@noindent 29001@code{gnatdll} takes as input a definition file @file{API.def} and the 29002name of the DLL containing the services listed in the definition file 29003@file{API.dll}. The name of the static import library generated is 29004computed from the name of the definition file as follows: if the 29005definition file name is @var{xyz}@code{.def}, the import library name will 29006be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option 29007@option{-e} could have been removed because the name of the definition 29008file (before the ``@code{.def}'' suffix) is the same as the name of the 29009DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}). 29010@end enumerate 29011 29012@node Microsoft-Style Import Library 29013@subsubsection Microsoft-Style Import Library 29014 29015@noindent 29016With GNAT you can either use a GNAT-style or Microsoft-style import 29017library. A Microsoft import library is needed only if you plan to make an 29018Ada DLL available to applications developed with Microsoft 29019tools (@pxref{Mixed-Language Programming on Windows}). 29020 29021To create a Microsoft-style import library for @file{API.dll} you 29022should proceed as follows: 29023 29024@enumerate 29025@item 29026Create the definition file @file{API.def} from the DLL. For this use either 29027the @code{dll2def} tool as described above or the Microsoft @code{dumpbin} 29028tool (see the corresponding Microsoft documentation for further details). 29029 29030@item 29031Build the actual import library using Microsoft's @code{lib} utility: 29032 29033@smallexample 29034$ lib -machine:IX86 -def:API.def -out:API.lib 29035@end smallexample 29036 29037@noindent 29038If you use the above command the definition file @file{API.def} must 29039contain a line giving the name of the DLL: 29040 29041@smallexample 29042LIBRARY "API" 29043@end smallexample 29044 29045@noindent 29046See the Microsoft documentation for further details about the usage of 29047@code{lib}. 29048@end enumerate 29049 29050@node Building DLLs with GNAT Project files 29051@section Building DLLs with GNAT Project files 29052@cindex DLLs, building 29053 29054@noindent 29055There is nothing specific to Windows in the build process. 29056@pxref{Library Projects}. 29057 29058@noindent 29059Due to a system limitation, it is not possible under Windows to create threads 29060when inside the @code{DllMain} routine which is used for auto-initialization 29061of shared libraries, so it is not possible to have library level tasks in SALs. 29062 29063@node Building DLLs with GNAT 29064@section Building DLLs with GNAT 29065@cindex DLLs, building 29066 29067@noindent 29068This section explain how to build DLLs using the GNAT built-in DLL 29069support. With the following procedure it is straight forward to build 29070and use DLLs with GNAT. 29071 29072@enumerate 29073 29074@item building object files 29075 29076The first step is to build all objects files that are to be included 29077into the DLL. This is done by using the standard @command{gnatmake} tool. 29078 29079@item building the DLL 29080 29081To build the DLL you must use @command{gcc}'s @option{-shared} and 29082@option{-shared-libgcc} options. It is quite simple to use this method: 29083 29084@smallexample 29085$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{} 29086@end smallexample 29087 29088It is important to note that in this case all symbols found in the 29089object files are automatically exported. It is possible to restrict 29090the set of symbols to export by passing to @command{gcc} a definition 29091file, @pxref{The Definition File}. For example: 29092 29093@smallexample 29094$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{} 29095@end smallexample 29096 29097If you use a definition file you must export the elaboration procedures 29098for every package that required one. Elaboration procedures are named 29099using the package name followed by "_E". 29100 29101@item preparing DLL to be used 29102 29103For the DLL to be used by client programs the bodies must be hidden 29104from it and the .ali set with read-only attribute. This is very important 29105otherwise GNAT will recompile all packages and will not actually use 29106the code in the DLL. For example: 29107 29108@smallexample 29109$ mkdir apilib 29110$ copy *.ads *.ali api.dll apilib 29111$ attrib +R apilib\*.ali 29112@end smallexample 29113 29114@end enumerate 29115 29116At this point it is possible to use the DLL by directly linking 29117against it. Note that you must use the GNAT shared runtime when using 29118GNAT shared libraries. This is achieved by using @option{-shared} binder's 29119option. 29120 29121@smallexample 29122$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI 29123@end smallexample 29124 29125@node Building DLLs with gnatdll 29126@section Building DLLs with gnatdll 29127@cindex DLLs, building 29128 29129@menu 29130* Limitations When Using Ada DLLs from Ada:: 29131* Exporting Ada Entities:: 29132* Ada DLLs and Elaboration:: 29133* Ada DLLs and Finalization:: 29134* Creating a Spec for Ada DLLs:: 29135* Creating the Definition File:: 29136* Using gnatdll:: 29137@end menu 29138 29139@noindent 29140Note that it is preferred to use GNAT Project files 29141(@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT 29142DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs. 29143 29144This section explains how to build DLLs containing Ada code using 29145@code{gnatdll}. These DLLs will be referred to as Ada DLLs in the 29146remainder of this section. 29147 29148The steps required to build an Ada DLL that is to be used by Ada as well as 29149non-Ada applications are as follows: 29150 29151@enumerate 29152@item 29153You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or 29154@code{Stdcall} calling convention to avoid any Ada name mangling for the 29155entities exported by the DLL (@pxref{Exporting Ada Entities}). You can 29156skip this step if you plan to use the Ada DLL only from Ada applications. 29157 29158@item 29159Your Ada code must export an initialization routine which calls the routine 29160@code{adainit} generated by @command{gnatbind} to perform the elaboration of 29161the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization 29162routine exported by the Ada DLL must be invoked by the clients of the DLL 29163to initialize the DLL. 29164 29165@item 29166When useful, the DLL should also export a finalization routine which calls 29167routine @code{adafinal} generated by @command{gnatbind} to perform the 29168finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}). 29169The finalization routine exported by the Ada DLL must be invoked by the 29170clients of the DLL when the DLL services are no further needed. 29171 29172@item 29173You must provide a spec for the services exported by the Ada DLL in each 29174of the programming languages to which you plan to make the DLL available. 29175 29176@item 29177You must provide a definition file listing the exported entities 29178(@pxref{The Definition File}). 29179 29180@item 29181Finally you must use @code{gnatdll} to produce the DLL and the import 29182library (@pxref{Using gnatdll}). 29183@end enumerate 29184 29185@noindent 29186Note that a relocatable DLL stripped using the @code{strip} 29187binutils tool will not be relocatable anymore. To build a DLL without 29188debug information pass @code{-largs -s} to @code{gnatdll}. This 29189restriction does not apply to a DLL built using a Library Project. 29190@pxref{Library Projects}. 29191 29192@node Limitations When Using Ada DLLs from Ada 29193@subsection Limitations When Using Ada DLLs from Ada 29194 29195@noindent 29196When using Ada DLLs from Ada applications there is a limitation users 29197should be aware of. Because on Windows the GNAT run time is not in a DLL of 29198its own, each Ada DLL includes a part of the GNAT run time. Specifically, 29199each Ada DLL includes the services of the GNAT run time that are necessary 29200to the Ada code inside the DLL. As a result, when an Ada program uses an 29201Ada DLL there are two independent GNAT run times: one in the Ada DLL and 29202one in the main program. 29203 29204It is therefore not possible to exchange GNAT run-time objects between the 29205Ada DLL and the main Ada program. Example of GNAT run-time objects are file 29206handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects 29207types, etc. 29208 29209It is completely safe to exchange plain elementary, array or record types, 29210Windows object handles, etc. 29211 29212@node Exporting Ada Entities 29213@subsection Exporting Ada Entities 29214@cindex Export table 29215 29216@noindent 29217Building a DLL is a way to encapsulate a set of services usable from any 29218application. As a result, the Ada entities exported by a DLL should be 29219exported with the @code{C} or @code{Stdcall} calling conventions to avoid 29220any Ada name mangling. As an example here is an Ada package 29221@code{API}, spec and body, exporting two procedures, a function, and a 29222variable: 29223 29224@smallexample @c ada 29225@group 29226@cartouche 29227with Interfaces.C; use Interfaces; 29228package API is 29229 Count : C.int := 0; 29230 function Factorial (Val : C.int) return C.int; 29231 29232 procedure Initialize_API; 29233 procedure Finalize_API; 29234 -- Initialization & Finalization routines. More in the next section. 29235private 29236 pragma Export (C, Initialize_API); 29237 pragma Export (C, Finalize_API); 29238 pragma Export (C, Count); 29239 pragma Export (C, Factorial); 29240end API; 29241@end cartouche 29242@end group 29243@end smallexample 29244 29245@smallexample @c ada 29246@group 29247@cartouche 29248package body API is 29249 function Factorial (Val : C.int) return C.int is 29250 Fact : C.int := 1; 29251 begin 29252 Count := Count + 1; 29253 for K in 1 .. Val loop 29254 Fact := Fact * K; 29255 end loop; 29256 return Fact; 29257 end Factorial; 29258 29259 procedure Initialize_API is 29260 procedure Adainit; 29261 pragma Import (C, Adainit); 29262 begin 29263 Adainit; 29264 end Initialize_API; 29265 29266 procedure Finalize_API is 29267 procedure Adafinal; 29268 pragma Import (C, Adafinal); 29269 begin 29270 Adafinal; 29271 end Finalize_API; 29272end API; 29273@end cartouche 29274@end group 29275@end smallexample 29276 29277@noindent 29278If the Ada DLL you are building will only be used by Ada applications 29279you do not have to export Ada entities with a @code{C} or @code{Stdcall} 29280convention. As an example, the previous package could be written as 29281follows: 29282 29283@smallexample @c ada 29284@group 29285@cartouche 29286package API is 29287 Count : Integer := 0; 29288 function Factorial (Val : Integer) return Integer; 29289 29290 procedure Initialize_API; 29291 procedure Finalize_API; 29292 -- Initialization and Finalization routines. 29293end API; 29294@end cartouche 29295@end group 29296@end smallexample 29297 29298@smallexample @c ada 29299@group 29300@cartouche 29301package body API is 29302 function Factorial (Val : Integer) return Integer is 29303 Fact : Integer := 1; 29304 begin 29305 Count := Count + 1; 29306 for K in 1 .. Val loop 29307 Fact := Fact * K; 29308 end loop; 29309 return Fact; 29310 end Factorial; 29311 29312 @dots{} 29313 -- The remainder of this package body is unchanged. 29314end API; 29315@end cartouche 29316@end group 29317@end smallexample 29318 29319@noindent 29320Note that if you do not export the Ada entities with a @code{C} or 29321@code{Stdcall} convention you will have to provide the mangled Ada names 29322in the definition file of the Ada DLL 29323(@pxref{Creating the Definition File}). 29324 29325@node Ada DLLs and Elaboration 29326@subsection Ada DLLs and Elaboration 29327@cindex DLLs and elaboration 29328 29329@noindent 29330The DLL that you are building contains your Ada code as well as all the 29331routines in the Ada library that are needed by it. The first thing a 29332user of your DLL must do is elaborate the Ada code 29333(@pxref{Elaboration Order Handling in GNAT}). 29334 29335To achieve this you must export an initialization routine 29336(@code{Initialize_API} in the previous example), which must be invoked 29337before using any of the DLL services. This elaboration routine must call 29338the Ada elaboration routine @code{adainit} generated by the GNAT binder 29339(@pxref{Binding with Non-Ada Main Programs}). See the body of 29340@code{Initialize_Api} for an example. Note that the GNAT binder is 29341automatically invoked during the DLL build process by the @code{gnatdll} 29342tool (@pxref{Using gnatdll}). 29343 29344When a DLL is loaded, Windows systematically invokes a routine called 29345@code{DllMain}. It would therefore be possible to call @code{adainit} 29346directly from @code{DllMain} without having to provide an explicit 29347initialization routine. Unfortunately, it is not possible to call 29348@code{adainit} from the @code{DllMain} if your program has library level 29349tasks because access to the @code{DllMain} entry point is serialized by 29350the system (that is, only a single thread can execute ``through'' it at a 29351time), which means that the GNAT run time will deadlock waiting for the 29352newly created task to complete its initialization. 29353 29354@node Ada DLLs and Finalization 29355@subsection Ada DLLs and Finalization 29356@cindex DLLs and finalization 29357 29358@noindent 29359When the services of an Ada DLL are no longer needed, the client code should 29360invoke the DLL finalization routine, if available. The DLL finalization 29361routine is in charge of releasing all resources acquired by the DLL. In the 29362case of the Ada code contained in the DLL, this is achieved by calling 29363routine @code{adafinal} generated by the GNAT binder 29364(@pxref{Binding with Non-Ada Main Programs}). 29365See the body of @code{Finalize_Api} for an 29366example. As already pointed out the GNAT binder is automatically invoked 29367during the DLL build process by the @code{gnatdll} tool 29368(@pxref{Using gnatdll}). 29369 29370@node Creating a Spec for Ada DLLs 29371@subsection Creating a Spec for Ada DLLs 29372 29373@noindent 29374To use the services exported by the Ada DLL from another programming 29375language (e.g.@: C), you have to translate the specs of the exported Ada 29376entities in that language. For instance in the case of @code{API.dll}, 29377the corresponding C header file could look like: 29378 29379@smallexample 29380@group 29381@cartouche 29382extern int *_imp__count; 29383#define count (*_imp__count) 29384int factorial (int); 29385@end cartouche 29386@end group 29387@end smallexample 29388 29389@noindent 29390It is important to understand that when building an Ada DLL to be used by 29391other Ada applications, you need two different specs for the packages 29392contained in the DLL: one for building the DLL and the other for using 29393the DLL. This is because the @code{DLL} calling convention is needed to 29394use a variable defined in a DLL, but when building the DLL, the variable 29395must have either the @code{Ada} or @code{C} calling convention. As an 29396example consider a DLL comprising the following package @code{API}: 29397 29398@smallexample @c ada 29399@group 29400@cartouche 29401package API is 29402 Count : Integer := 0; 29403 @dots{} 29404 -- Remainder of the package omitted. 29405end API; 29406@end cartouche 29407@end group 29408@end smallexample 29409 29410@noindent 29411After producing a DLL containing package @code{API}, the spec that 29412must be used to import @code{API.Count} from Ada code outside of the 29413DLL is: 29414 29415@smallexample @c ada 29416@group 29417@cartouche 29418package API is 29419 Count : Integer; 29420 pragma Import (DLL, Count); 29421end API; 29422@end cartouche 29423@end group 29424@end smallexample 29425 29426@node Creating the Definition File 29427@subsection Creating the Definition File 29428 29429@noindent 29430The definition file is the last file needed to build the DLL. It lists 29431the exported symbols. As an example, the definition file for a DLL 29432containing only package @code{API} (where all the entities are exported 29433with a @code{C} calling convention) is: 29434 29435@smallexample 29436@group 29437@cartouche 29438EXPORTS 29439 count 29440 factorial 29441 finalize_api 29442 initialize_api 29443@end cartouche 29444@end group 29445@end smallexample 29446 29447@noindent 29448If the @code{C} calling convention is missing from package @code{API}, 29449then the definition file contains the mangled Ada names of the above 29450entities, which in this case are: 29451 29452@smallexample 29453@group 29454@cartouche 29455EXPORTS 29456 api__count 29457 api__factorial 29458 api__finalize_api 29459 api__initialize_api 29460@end cartouche 29461@end group 29462@end smallexample 29463 29464@node Using gnatdll 29465@subsection Using @code{gnatdll} 29466@findex gnatdll 29467 29468@menu 29469* gnatdll Example:: 29470* gnatdll behind the Scenes:: 29471* Using dlltool:: 29472@end menu 29473 29474@noindent 29475@code{gnatdll} is a tool to automate the DLL build process once all the Ada 29476and non-Ada sources that make up your DLL have been compiled. 29477@code{gnatdll} is actually in charge of two distinct tasks: build the 29478static import library for the DLL and the actual DLL. The form of the 29479@code{gnatdll} command is 29480 29481@smallexample 29482@cartouche 29483@c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]} 29484@c Expanding @ovar macro inline (explanation in macro def comments) 29485$ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]} 29486@end cartouche 29487@end smallexample 29488 29489@noindent 29490where @var{list-of-files} is a list of ALI and object files. The object 29491file list must be the exact list of objects corresponding to the non-Ada 29492sources whose services are to be included in the DLL. The ALI file list 29493must be the exact list of ALI files for the corresponding Ada sources 29494whose services are to be included in the DLL. If @var{list-of-files} is 29495missing, only the static import library is generated. 29496 29497@noindent 29498You may specify any of the following switches to @code{gnatdll}: 29499 29500@table @code 29501@c @item -a@ovar{address} 29502@c Expanding @ovar macro inline (explanation in macro def comments) 29503@item -a@r{[}@var{address}@r{]} 29504@cindex @option{-a} (@code{gnatdll}) 29505Build a non-relocatable DLL at @var{address}. If @var{address} is not 29506specified the default address @var{0x11000000} will be used. By default, 29507when this switch is missing, @code{gnatdll} builds relocatable DLL. We 29508advise the reader to build relocatable DLL. 29509 29510@item -b @var{address} 29511@cindex @option{-b} (@code{gnatdll}) 29512Set the relocatable DLL base address. By default the address is 29513@code{0x11000000}. 29514 29515@item -bargs @var{opts} 29516@cindex @option{-bargs} (@code{gnatdll}) 29517Binder options. Pass @var{opts} to the binder. 29518 29519@item -d @var{dllfile} 29520@cindex @option{-d} (@code{gnatdll}) 29521@var{dllfile} is the name of the DLL. This switch must be present for 29522@code{gnatdll} to do anything. The name of the generated import library is 29523obtained algorithmically from @var{dllfile} as shown in the following 29524example: if @var{dllfile} is @code{xyz.dll}, the import library name is 29525@code{libxyz.dll.a}. The name of the definition file to use (if not specified 29526by option @option{-e}) is obtained algorithmically from @var{dllfile} 29527as shown in the following example: 29528if @var{dllfile} is @code{xyz.dll}, the definition 29529file used is @code{xyz.def}. 29530 29531@item -e @var{deffile} 29532@cindex @option{-e} (@code{gnatdll}) 29533@var{deffile} is the name of the definition file. 29534 29535@item -g 29536@cindex @option{-g} (@code{gnatdll}) 29537Generate debugging information. This information is stored in the object 29538file and copied from there to the final DLL file by the linker, 29539where it can be read by the debugger. You must use the 29540@option{-g} switch if you plan on using the debugger or the symbolic 29541stack traceback. 29542 29543@item -h 29544@cindex @option{-h} (@code{gnatdll}) 29545Help mode. Displays @code{gnatdll} switch usage information. 29546 29547@item -Idir 29548@cindex @option{-I} (@code{gnatdll}) 29549Direct @code{gnatdll} to search the @var{dir} directory for source and 29550object files needed to build the DLL. 29551(@pxref{Search Paths and the Run-Time Library (RTL)}). 29552 29553@item -k 29554@cindex @option{-k} (@code{gnatdll}) 29555Removes the @code{@@}@var{nn} suffix from the import library's exported 29556names, but keeps them for the link names. You must specify this 29557option if you want to use a @code{Stdcall} function in a DLL for which 29558the @code{@@}@var{nn} suffix has been removed. This is the case for most 29559of the Windows NT DLL for example. This option has no effect when 29560@option{-n} option is specified. 29561 29562@item -l @var{file} 29563@cindex @option{-l} (@code{gnatdll}) 29564The list of ALI and object files used to build the DLL are listed in 29565@var{file}, instead of being given in the command line. Each line in 29566@var{file} contains the name of an ALI or object file. 29567 29568@item -n 29569@cindex @option{-n} (@code{gnatdll}) 29570No Import. Do not create the import library. 29571 29572@item -q 29573@cindex @option{-q} (@code{gnatdll}) 29574Quiet mode. Do not display unnecessary messages. 29575 29576@item -v 29577@cindex @option{-v} (@code{gnatdll}) 29578Verbose mode. Display extra information. 29579 29580@item -largs @var{opts} 29581@cindex @option{-largs} (@code{gnatdll}) 29582Linker options. Pass @var{opts} to the linker. 29583@end table 29584 29585@node gnatdll Example 29586@subsubsection @code{gnatdll} Example 29587 29588@noindent 29589As an example the command to build a relocatable DLL from @file{api.adb} 29590once @file{api.adb} has been compiled and @file{api.def} created is 29591 29592@smallexample 29593$ gnatdll -d api.dll api.ali 29594@end smallexample 29595 29596@noindent 29597The above command creates two files: @file{libapi.dll.a} (the import 29598library) and @file{api.dll} (the actual DLL). If you want to create 29599only the DLL, just type: 29600 29601@smallexample 29602$ gnatdll -d api.dll -n api.ali 29603@end smallexample 29604 29605@noindent 29606Alternatively if you want to create just the import library, type: 29607 29608@smallexample 29609$ gnatdll -d api.dll 29610@end smallexample 29611 29612@node gnatdll behind the Scenes 29613@subsubsection @code{gnatdll} behind the Scenes 29614 29615@noindent 29616This section details the steps involved in creating a DLL. @code{gnatdll} 29617does these steps for you. Unless you are interested in understanding what 29618goes on behind the scenes, you should skip this section. 29619 29620We use the previous example of a DLL containing the Ada package @code{API}, 29621to illustrate the steps necessary to build a DLL. The starting point is a 29622set of objects that will make up the DLL and the corresponding ALI 29623files. In the case of this example this means that @file{api.o} and 29624@file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does 29625the following: 29626 29627@enumerate 29628@item 29629@code{gnatdll} builds the base file (@file{api.base}). A base file gives 29630the information necessary to generate relocation information for the 29631DLL. 29632 29633@smallexample 29634@group 29635$ gnatbind -n api 29636$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base 29637@end group 29638@end smallexample 29639 29640@noindent 29641In addition to the base file, the @command{gnatlink} command generates an 29642output file @file{api.jnk} which can be discarded. The @option{-mdll} switch 29643asks @command{gnatlink} to generate the routines @code{DllMain} and 29644@code{DllMainCRTStartup} that are called by the Windows loader when the DLL 29645is loaded into memory. 29646 29647@item 29648@code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the 29649export table (@file{api.exp}). The export table contains the relocation 29650information in a form which can be used during the final link to ensure 29651that the Windows loader is able to place the DLL anywhere in memory. 29652 29653@smallexample 29654@group 29655$ dlltool --dllname api.dll --def api.def --base-file api.base \ 29656 --output-exp api.exp 29657@end group 29658@end smallexample 29659 29660@item 29661@code{gnatdll} builds the base file using the new export table. Note that 29662@command{gnatbind} must be called once again since the binder generated file 29663has been deleted during the previous call to @command{gnatlink}. 29664 29665@smallexample 29666@group 29667$ gnatbind -n api 29668$ gnatlink api -o api.jnk api.exp -mdll 29669 -Wl,--base-file,api.base 29670@end group 29671@end smallexample 29672 29673@item 29674@code{gnatdll} builds the new export table using the new base file and 29675generates the DLL import library @file{libAPI.dll.a}. 29676 29677@smallexample 29678@group 29679$ dlltool --dllname api.dll --def api.def --base-file api.base \ 29680 --output-exp api.exp --output-lib libAPI.a 29681@end group 29682@end smallexample 29683 29684@item 29685Finally @code{gnatdll} builds the relocatable DLL using the final export 29686table. 29687 29688@smallexample 29689@group 29690$ gnatbind -n api 29691$ gnatlink api api.exp -o api.dll -mdll 29692@end group 29693@end smallexample 29694@end enumerate 29695 29696@node Using dlltool 29697@subsubsection Using @code{dlltool} 29698 29699@noindent 29700@code{dlltool} is the low-level tool used by @code{gnatdll} to build 29701DLLs and static import libraries. This section summarizes the most 29702common @code{dlltool} switches. The form of the @code{dlltool} command 29703is 29704 29705@smallexample 29706@c $ dlltool @ovar{switches} 29707@c Expanding @ovar macro inline (explanation in macro def comments) 29708$ dlltool @r{[}@var{switches}@r{]} 29709@end smallexample 29710 29711@noindent 29712@code{dlltool} switches include: 29713 29714@table @option 29715@item --base-file @var{basefile} 29716@cindex @option{--base-file} (@command{dlltool}) 29717Read the base file @var{basefile} generated by the linker. This switch 29718is used to create a relocatable DLL. 29719 29720@item --def @var{deffile} 29721@cindex @option{--def} (@command{dlltool}) 29722Read the definition file. 29723 29724@item --dllname @var{name} 29725@cindex @option{--dllname} (@command{dlltool}) 29726Gives the name of the DLL. This switch is used to embed the name of the 29727DLL in the static import library generated by @code{dlltool} with switch 29728@option{--output-lib}. 29729 29730@item -k 29731@cindex @option{-k} (@command{dlltool}) 29732Kill @code{@@}@var{nn} from exported names 29733(@pxref{Windows Calling Conventions} 29734for a discussion about @code{Stdcall}-style symbols. 29735 29736@item --help 29737@cindex @option{--help} (@command{dlltool}) 29738Prints the @code{dlltool} switches with a concise description. 29739 29740@item --output-exp @var{exportfile} 29741@cindex @option{--output-exp} (@command{dlltool}) 29742Generate an export file @var{exportfile}. The export file contains the 29743export table (list of symbols in the DLL) and is used to create the DLL. 29744 29745@item --output-lib @var{libfile} 29746@cindex @option{--output-lib} (@command{dlltool}) 29747Generate a static import library @var{libfile}. 29748 29749@item -v 29750@cindex @option{-v} (@command{dlltool}) 29751Verbose mode. 29752 29753@item --as @var{assembler-name} 29754@cindex @option{--as} (@command{dlltool}) 29755Use @var{assembler-name} as the assembler. The default is @code{as}. 29756@end table 29757 29758@node GNAT and Windows Resources 29759@section GNAT and Windows Resources 29760@cindex Resources, windows 29761 29762@menu 29763* Building Resources:: 29764* Compiling Resources:: 29765* Using Resources:: 29766@end menu 29767 29768@noindent 29769Resources are an easy way to add Windows specific objects to your 29770application. The objects that can be added as resources include: 29771 29772@itemize @bullet 29773@item menus 29774 29775@item accelerators 29776 29777@item dialog boxes 29778 29779@item string tables 29780 29781@item bitmaps 29782 29783@item cursors 29784 29785@item icons 29786 29787@item fonts 29788 29789@item version information 29790@end itemize 29791 29792For example, a version information resource can be defined as follow and 29793embedded into an executable or DLL: 29794 29795A version information resource can be used to embed information into an 29796executable or a DLL. These information can be viewed using the file properties 29797from the Windows Explorer. Here is an example of a version information 29798resource: 29799 29800@smallexample 29801@group 298021 VERSIONINFO 29803FILEVERSION 1,0,0,0 29804PRODUCTVERSION 1,0,0,0 29805BEGIN 29806 BLOCK "StringFileInfo" 29807 BEGIN 29808 BLOCK "080904E4" 29809 BEGIN 29810 VALUE "CompanyName", "My Company Name" 29811 VALUE "FileDescription", "My application" 29812 VALUE "FileVersion", "1.0" 29813 VALUE "InternalName", "my_app" 29814 VALUE "LegalCopyright", "My Name" 29815 VALUE "OriginalFilename", "my_app.exe" 29816 VALUE "ProductName", "My App" 29817 VALUE "ProductVersion", "1.0" 29818 END 29819 END 29820 29821 BLOCK "VarFileInfo" 29822 BEGIN 29823 VALUE "Translation", 0x809, 1252 29824 END 29825END 29826@end group 29827@end smallexample 29828 29829The value @code{0809} (langID) is for the U.K English language and 29830@code{04E4} (charsetID), which is equal to @code{1252} decimal, for 29831multilingual. 29832 29833@noindent 29834This section explains how to build, compile and use resources. Note that this 29835section does not cover all resource objects, for a complete description see 29836the corresponding Microsoft documentation. 29837 29838@node Building Resources 29839@subsection Building Resources 29840@cindex Resources, building 29841 29842@noindent 29843A resource file is an ASCII file. By convention resource files have an 29844@file{.rc} extension. 29845The easiest way to build a resource file is to use Microsoft tools 29846such as @code{imagedit.exe} to build bitmaps, icons and cursors and 29847@code{dlgedit.exe} to build dialogs. 29848It is always possible to build an @file{.rc} file yourself by writing a 29849resource script. 29850 29851It is not our objective to explain how to write a resource file. A 29852complete description of the resource script language can be found in the 29853Microsoft documentation. 29854 29855@node Compiling Resources 29856@subsection Compiling Resources 29857@findex rc 29858@findex windres 29859@cindex Resources, compiling 29860 29861@noindent 29862This section describes how to build a GNAT-compatible (COFF) object file 29863containing the resources. This is done using the Resource Compiler 29864@code{windres} as follows: 29865 29866@smallexample 29867$ windres -i myres.rc -o myres.o 29868@end smallexample 29869 29870@noindent 29871By default @code{windres} will run @command{gcc} to preprocess the @file{.rc} 29872file. You can specify an alternate preprocessor (usually named 29873@file{cpp.exe}) using the @code{windres} @option{--preprocessor} 29874parameter. A list of all possible options may be obtained by entering 29875the command @code{windres} @option{--help}. 29876 29877It is also possible to use the Microsoft resource compiler @code{rc.exe} 29878to produce a @file{.res} file (binary resource file). See the 29879corresponding Microsoft documentation for further details. In this case 29880you need to use @code{windres} to translate the @file{.res} file to a 29881GNAT-compatible object file as follows: 29882 29883@smallexample 29884$ windres -i myres.res -o myres.o 29885@end smallexample 29886 29887@node Using Resources 29888@subsection Using Resources 29889@cindex Resources, using 29890 29891@noindent 29892To include the resource file in your program just add the 29893GNAT-compatible object file for the resource(s) to the linker 29894arguments. With @command{gnatmake} this is done by using the @option{-largs} 29895option: 29896 29897@smallexample 29898$ gnatmake myprog -largs myres.o 29899@end smallexample 29900 29901@node Debugging a DLL 29902@section Debugging a DLL 29903@cindex DLL debugging 29904 29905@menu 29906* Program and DLL Both Built with GCC/GNAT:: 29907* Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 29908@end menu 29909 29910@noindent 29911Debugging a DLL is similar to debugging a standard program. But 29912we have to deal with two different executable parts: the DLL and the 29913program that uses it. We have the following four possibilities: 29914 29915@enumerate 1 29916@item 29917The program and the DLL are built with @code{GCC/GNAT}. 29918@item 29919The program is built with foreign tools and the DLL is built with 29920@code{GCC/GNAT}. 29921@item 29922The program is built with @code{GCC/GNAT} and the DLL is built with 29923foreign tools. 29924@end enumerate 29925 29926@noindent 29927In this section we address only cases one and two above. 29928There is no point in trying to debug 29929a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging 29930information in it. To do so you must use a debugger compatible with the 29931tools suite used to build the DLL. 29932 29933@node Program and DLL Both Built with GCC/GNAT 29934@subsection Program and DLL Both Built with GCC/GNAT 29935 29936@noindent 29937This is the simplest case. Both the DLL and the program have @code{GDB} 29938compatible debugging information. It is then possible to break anywhere in 29939the process. Let's suppose here that the main procedure is named 29940@code{ada_main} and that in the DLL there is an entry point named 29941@code{ada_dll}. 29942 29943@noindent 29944The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and 29945program must have been built with the debugging information (see GNAT -g 29946switch). Here are the step-by-step instructions for debugging it: 29947 29948@enumerate 1 29949@item Launch @code{GDB} on the main program. 29950 29951@smallexample 29952$ gdb -nw ada_main 29953@end smallexample 29954 29955@item Start the program and stop at the beginning of the main procedure 29956 29957@smallexample 29958(gdb) start 29959@end smallexample 29960 29961@noindent 29962This step is required to be able to set a breakpoint inside the DLL. As long 29963as the program is not run, the DLL is not loaded. This has the 29964consequence that the DLL debugging information is also not loaded, so it is not 29965possible to set a breakpoint in the DLL. 29966 29967@item Set a breakpoint inside the DLL 29968 29969@smallexample 29970(gdb) break ada_dll 29971(gdb) cont 29972@end smallexample 29973 29974@end enumerate 29975 29976@noindent 29977At this stage a breakpoint is set inside the DLL. From there on 29978you can use the standard approach to debug the whole program 29979(@pxref{Running and Debugging Ada Programs}). 29980 29981@ignore 29982@c This used to work, probably because the DLLs were non-relocatable 29983@c keep this section around until the problem is sorted out. 29984 29985To break on the @code{DllMain} routine it is not possible to follow 29986the procedure above. At the time the program stop on @code{ada_main} 29987the @code{DllMain} routine as already been called. Either you can use 29988the procedure below @pxref{Debugging the DLL Directly} or this procedure: 29989 29990@enumerate 1 29991@item Launch @code{GDB} on the main program. 29992 29993@smallexample 29994$ gdb ada_main 29995@end smallexample 29996 29997@item Load DLL symbols 29998 29999@smallexample 30000(gdb) add-sym api.dll 30001@end smallexample 30002 30003@item Set a breakpoint inside the DLL 30004 30005@smallexample 30006(gdb) break ada_dll.adb:45 30007@end smallexample 30008 30009Note that at this point it is not possible to break using the routine symbol 30010directly as the program is not yet running. The solution is to break 30011on the proper line (break in @file{ada_dll.adb} line 45). 30012 30013@item Start the program 30014 30015@smallexample 30016(gdb) run 30017@end smallexample 30018 30019@end enumerate 30020@end ignore 30021 30022@node Program Built with Foreign Tools and DLL Built with GCC/GNAT 30023@subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT 30024 30025@menu 30026* Debugging the DLL Directly:: 30027* Attaching to a Running Process:: 30028@end menu 30029 30030@noindent 30031In this case things are slightly more complex because it is not possible to 30032start the main program and then break at the beginning to load the DLL and the 30033associated DLL debugging information. It is not possible to break at the 30034beginning of the program because there is no @code{GDB} debugging information, 30035and therefore there is no direct way of getting initial control. This 30036section addresses this issue by describing some methods that can be used 30037to break somewhere in the DLL to debug it. 30038 30039@noindent 30040First suppose that the main procedure is named @code{main} (this is for 30041example some C code built with Microsoft Visual C) and that there is a 30042DLL named @code{test.dll} containing an Ada entry point named 30043@code{ada_dll}. 30044 30045@noindent 30046The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have 30047been built with debugging information (see GNAT -g option). 30048 30049@node Debugging the DLL Directly 30050@subsubsection Debugging the DLL Directly 30051 30052@enumerate 1 30053@item 30054Find out the executable starting address 30055 30056@smallexample 30057$ objdump --file-header main.exe 30058@end smallexample 30059 30060The starting address is reported on the last line. For example: 30061 30062@smallexample 30063main.exe: file format pei-i386 30064architecture: i386, flags 0x0000010a: 30065EXEC_P, HAS_DEBUG, D_PAGED 30066start address 0x00401010 30067@end smallexample 30068 30069@item 30070Launch the debugger on the executable. 30071 30072@smallexample 30073$ gdb main.exe 30074@end smallexample 30075 30076@item 30077Set a breakpoint at the starting address, and launch the program. 30078 30079@smallexample 30080$ (gdb) break *0x00401010 30081$ (gdb) run 30082@end smallexample 30083 30084The program will stop at the given address. 30085 30086@item 30087Set a breakpoint on a DLL subroutine. 30088 30089@smallexample 30090(gdb) break ada_dll.adb:45 30091@end smallexample 30092 30093Or if you want to break using a symbol on the DLL, you need first to 30094select the Ada language (language used by the DLL). 30095 30096@smallexample 30097(gdb) set language ada 30098(gdb) break ada_dll 30099@end smallexample 30100 30101@item 30102Continue the program. 30103 30104@smallexample 30105(gdb) cont 30106@end smallexample 30107 30108@noindent 30109This will run the program until it reaches the breakpoint that has been 30110set. From that point you can use the standard way to debug a program 30111as described in (@pxref{Running and Debugging Ada Programs}). 30112 30113@end enumerate 30114 30115@noindent 30116It is also possible to debug the DLL by attaching to a running process. 30117 30118@node Attaching to a Running Process 30119@subsubsection Attaching to a Running Process 30120@cindex DLL debugging, attach to process 30121 30122@noindent 30123With @code{GDB} it is always possible to debug a running process by 30124attaching to it. It is possible to debug a DLL this way. The limitation 30125of this approach is that the DLL must run long enough to perform the 30126attach operation. It may be useful for instance to insert a time wasting 30127loop in the code of the DLL to meet this criterion. 30128 30129@enumerate 1 30130 30131@item Launch the main program @file{main.exe}. 30132 30133@smallexample 30134$ main 30135@end smallexample 30136 30137@item Use the Windows @i{Task Manager} to find the process ID. Let's say 30138that the process PID for @file{main.exe} is 208. 30139 30140@item Launch gdb. 30141 30142@smallexample 30143$ gdb 30144@end smallexample 30145 30146@item Attach to the running process to be debugged. 30147 30148@smallexample 30149(gdb) attach 208 30150@end smallexample 30151 30152@item Load the process debugging information. 30153 30154@smallexample 30155(gdb) symbol-file main.exe 30156@end smallexample 30157 30158@item Break somewhere in the DLL. 30159 30160@smallexample 30161(gdb) break ada_dll 30162@end smallexample 30163 30164@item Continue process execution. 30165 30166@smallexample 30167(gdb) cont 30168@end smallexample 30169 30170@end enumerate 30171 30172@noindent 30173This last step will resume the process execution, and stop at 30174the breakpoint we have set. From there you can use the standard 30175approach to debug a program as described in 30176(@pxref{Running and Debugging Ada Programs}). 30177 30178@node Setting Stack Size from gnatlink 30179@section Setting Stack Size from @command{gnatlink} 30180 30181@noindent 30182It is possible to specify the program stack size at link time. On modern 30183versions of Windows, starting with XP, this is mostly useful to set the size of 30184the main stack (environment task). The other task stacks are set with pragma 30185Storage_Size or with the @command{gnatbind -d} command. 30186 30187Since older versions of Windows (2000, NT4, etc.) do not allow setting the 30188reserve size of individual tasks, the link-time stack size applies to all 30189tasks, and pragma Storage_Size has no effect. 30190In particular, Stack Overflow checks are made against this 30191link-time specified size. 30192 30193This setting can be done with 30194@command{gnatlink} using either: 30195 30196@itemize @bullet 30197 30198@item using @option{-Xlinker} linker option 30199 30200@smallexample 30201$ gnatlink hello -Xlinker --stack=0x10000,0x1000 30202@end smallexample 30203 30204This sets the stack reserve size to 0x10000 bytes and the stack commit 30205size to 0x1000 bytes. 30206 30207@item using @option{-Wl} linker option 30208 30209@smallexample 30210$ gnatlink hello -Wl,--stack=0x1000000 30211@end smallexample 30212 30213This sets the stack reserve size to 0x1000000 bytes. Note that with 30214@option{-Wl} option it is not possible to set the stack commit size 30215because the coma is a separator for this option. 30216 30217@end itemize 30218 30219@node Setting Heap Size from gnatlink 30220@section Setting Heap Size from @command{gnatlink} 30221 30222@noindent 30223Under Windows systems, it is possible to specify the program heap size from 30224@command{gnatlink} using either: 30225 30226@itemize @bullet 30227 30228@item using @option{-Xlinker} linker option 30229 30230@smallexample 30231$ gnatlink hello -Xlinker --heap=0x10000,0x1000 30232@end smallexample 30233 30234This sets the heap reserve size to 0x10000 bytes and the heap commit 30235size to 0x1000 bytes. 30236 30237@item using @option{-Wl} linker option 30238 30239@smallexample 30240$ gnatlink hello -Wl,--heap=0x1000000 30241@end smallexample 30242 30243This sets the heap reserve size to 0x1000000 bytes. Note that with 30244@option{-Wl} option it is not possible to set the heap commit size 30245because the coma is a separator for this option. 30246 30247@end itemize 30248 30249@node Mac OS Topics 30250@appendix Mac OS Topics 30251@cindex OS X 30252 30253@noindent 30254This chapter describes topics that are specific to Apple's OS X 30255platform. 30256 30257@menu 30258* Codesigning the Debugger:: 30259@end menu 30260 30261@node Codesigning the Debugger 30262@section Codesigning the Debugger 30263 30264@noindent 30265The Darwin Kernel requires the debugger to have special permissions 30266before it is allowed to control other processes. These permissions 30267are granted by codesigning the GDB executable. Without these 30268permissions, the debugger will report error messages such as: 30269 30270@smallexample 30271Starting program: /x/y/foo 30272Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5). 30273 (please check gdb is codesigned - see taskgated(8)) 30274@end smallexample 30275 30276Codesigning requires a certificate. The following procedure explains 30277how to create one: 30278 30279@itemize @bullet 30280@item Start the Keychain Access application (in 30281/Applications/Utilities/Keychain Access.app) 30282 30283@item Select the Keychain Access -> Certificate Assistant -> 30284Create a Certificate... menu 30285 30286@item Then: 30287 30288@itemize @bullet 30289@item Choose a name for the new certificate (this procedure will use 30290"gdb-cert" as an example) 30291 30292@item Set "Identity Type" to "Self Signed Root" 30293 30294@item Set "Certificate Type" to "Code Signing" 30295 30296@item Activate the "Let me override defaults" option 30297 30298@end itemize 30299 30300@item Click several times on "Continue" until the "Specify a Location 30301For The Certificate" screen appears, then set "Keychain" to "System" 30302 30303@item Click on "Continue" until the certificate is created 30304 30305@item Finally, in the view, double-click on the new certificate, 30306and set "When using this certificate" to "Always Trust" 30307 30308@item Exit the Keychain Access application and restart the computer 30309(this is unfortunately required) 30310 30311@end itemize 30312 30313Once a certificate has been created, the debugger can be codesigned 30314as follow. In a Terminal, run the following command... 30315 30316@smallexample 30317codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb 30318@end smallexample 30319 30320... where "gdb-cert" should be replaced by the actual certificate 30321name chosen above, and <gnat_install_prefix> should be replaced by 30322the location where you installed GNAT. 30323 30324@end ifset 30325 30326@c ********************************** 30327@c * GNU Free Documentation License * 30328@c ********************************** 30329@include fdl.texi 30330@c GNU Free Documentation License 30331 30332@node Index,,GNU Free Documentation License, Top 30333@unnumbered Index 30334 30335@printindex cp 30336 30337@contents 30338@c Put table of contents at end, otherwise it precedes the "title page" in 30339@c the .txt version 30340@c Edit the pdf file to move the contents to the beginning, after the title 30341@c page 30342 30343@bye 30344