1.. role:: switch(samp) 2 3.. |with| replace:: *with* 4.. |withs| replace:: *with*\ s 5.. |withed| replace:: *with*\ ed 6.. |withing| replace:: *with*\ ing 7 8.. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit 9 10 11.. _The_GNAT_Compilation_Model: 12 13************************** 14The GNAT Compilation Model 15************************** 16 17.. index:: ! GNAT compilation model 18 19.. index:: Compilation model 20 21This chapter describes the compilation model used by GNAT. Although 22similar to that used by other languages such as C and C++, this model 23is substantially different from the traditional Ada compilation models, 24which are based on a centralized program library. The chapter covers 25the following material: 26 27* Topics related to source file makeup and naming 28 29 * :ref:`Source_Representation` 30 * :ref:`Foreign_Language_Representation` 31 * :ref:`File_Naming_Topics_and_Utilities` 32 33* :ref:`Configuration_Pragmas` 34* :ref:`Generating_Object_Files` 35* :ref:`Source_Dependencies` 36* :ref:`The_Ada_Library_Information_Files` 37* :ref:`Binding_an_Ada_Program` 38* :ref:`GNAT_and_Libraries` 39* :ref:`Conditional_Compilation` 40* :ref:`Mixed_Language_Programming` 41* :ref:`GNAT_and_Other_Compilation_Models` 42* :ref:`Using_GNAT_Files_with_External_Tools` 43 44 45.. _Source_Representation: 46 47Source Representation 48===================== 49 50.. index:: Latin-1 51 52.. index:: VT, HT, CR, LF, FF 53 54Ada source programs are represented in standard text files, using 55Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar 567-bit ASCII set, plus additional characters used for 57representing foreign languages (see :ref:`Foreign_Language_Representation` 58for support of non-USA character sets). The format effector characters 59are represented using their standard ASCII encodings, as follows: 60 61 =========== ======================= =========== 62 Character Effect Code 63 ----------- ----------------------- ----------- 64 :kbd:`VT` Vertical tab ``16#0B#`` 65 :kbd:`HT` Horizontal tab ``16#09#`` 66 :kbd:`CR` Carriage return ``16#0D#`` 67 :kbd:`LF` Line feed ``16#0A#`` 68 :kbd:`FF` Form feed ``16#0C#`` 69 =========== ======================= =========== 70 71Source files are in standard text file format. In addition, GNAT will 72recognize a wide variety of stream formats, in which the end of 73physical lines is marked by any of the following sequences: 74``LF``, ``CR``, ``CR-LF``, or ``LF-CR``. This is useful 75in accommodating files that are imported from other operating systems. 76 77.. index:: pair: End of source file; Source file, end 78 79.. index:: SUB (control character) 80 81The end of a source file is normally represented by the physical end of 82file. However, the control character ``16#1A#`` (:kbd:`SUB`) is also 83recognized as signalling the end of the source file. Again, this is 84provided for compatibility with other operating systems where this 85code is used to represent the end of file. 86 87.. index:: spec (definition), compilation (definition) 88 89Each file contains a single Ada compilation unit, including any pragmas 90associated with the unit. For example, this means you must place a 91package declaration (a package *spec*) and the corresponding body in 92separate files. An Ada *compilation* (which is a sequence of 93compilation units) is represented using a sequence of files. Similarly, 94you will place each subunit or child unit in a separate file. 95 96.. _Foreign_Language_Representation: 97 98Foreign Language Representation 99=============================== 100 101GNAT supports the standard character sets defined in Ada as well as 102several other non-standard character sets for use in localized versions 103of the compiler (:ref:`Character_Set_Control`). 104 105.. _Latin-1: 106 107Latin-1 108------- 109 110.. index:: Latin-1 111 112The basic character set is Latin-1. This character set is defined by ISO 113standard 8859, part 1. The lower half (character codes ``16#00#`` 114... ``16#7F#)`` is identical to standard ASCII coding, but the upper 115half is used to represent additional characters. These include extended letters 116used by European languages, such as French accents, the vowels with umlauts 117used in German, and the extra letter A-ring used in Swedish. 118 119.. index:: Ada.Characters.Latin_1 120 121For a complete list of Latin-1 codes and their encodings, see the source 122file of library unit ``Ada.Characters.Latin_1`` in file 123:file:`a-chlat1.ads`. 124You may use any of these extended characters freely in character or 125string literals. In addition, the extended characters that represent 126letters can be used in identifiers. 127 128.. _Other_8-Bit_Codes: 129 130Other 8-Bit Codes 131----------------- 132 133GNAT also supports several other 8-bit coding schemes: 134 135 136.. index:: Latin-2 137.. index:: ISO 8859-2 138 139*ISO 8859-2 (Latin-2)* 140 Latin-2 letters allowed in identifiers, with uppercase and lowercase 141 equivalence. 142 143.. index:: Latin-3 144.. index:: ISO 8859-3 145 146*ISO 8859-3 (Latin-3)* 147 Latin-3 letters allowed in identifiers, with uppercase and lowercase 148 equivalence. 149 150 151.. index:: Latin-4 152.. index:: ISO 8859-4 153 154*ISO 8859-4 (Latin-4)* 155 Latin-4 letters allowed in identifiers, with uppercase and lowercase 156 equivalence. 157 158 159.. index:: ISO 8859-5 160.. index:: Cyrillic 161 162*ISO 8859-5 (Cyrillic)* 163 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and 164 lowercase equivalence. 165 166.. index:: ISO 8859-15 167.. index:: Latin-9 168 169*ISO 8859-15 (Latin-9)* 170 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and 171 lowercase equivalence 172 173.. index:: code page 437 (IBM PC) 174 175*IBM PC (code page 437)* 176 This code page is the normal default for PCs in the U.S. It corresponds 177 to the original IBM PC character set. This set has some, but not all, of 178 the extended Latin-1 letters, but these letters do not have the same 179 encoding as Latin-1. In this mode, these letters are allowed in 180 identifiers with uppercase and lowercase equivalence. 181 182.. index:: code page 850 (IBM PC) 183 184*IBM PC (code page 850)* 185 This code page is a modification of 437 extended to include all the 186 Latin-1 letters, but still not with the usual Latin-1 encoding. In this 187 mode, all these letters are allowed in identifiers with uppercase and 188 lowercase equivalence. 189 190 191*Full Upper 8-bit* 192 Any character in the range 80-FF allowed in identifiers, and all are 193 considered distinct. In other words, there are no uppercase and lowercase 194 equivalences in this range. This is useful in conjunction with 195 certain encoding schemes used for some foreign character sets (e.g., 196 the typical method of representing Chinese characters on the PC). 197 198 199*No Upper-Half* 200 No upper-half characters in the range 80-FF are allowed in identifiers. 201 This gives Ada 83 compatibility for identifier names. 202 203For precise data on the encodings permitted, and the uppercase and lowercase 204equivalences that are recognized, see the file :file:`csets.adb` in 205the GNAT compiler sources. You will need to obtain a full source release 206of GNAT to obtain this file. 207 208.. _Wide_Character_Encodings: 209 210Wide_Character Encodings 211------------------------ 212 213GNAT allows wide character codes to appear in character and string 214literals, and also optionally in identifiers, by means of the following 215possible encoding schemes: 216 217*Hex Coding* 218 In this encoding, a wide character is represented by the following five 219 character sequence:: 220 221 ESC a b c d 222 223 where ``a``, ``b``, ``c``, ``d`` are the four hexadecimal 224 characters (using uppercase letters) of the wide character code. For 225 example, ESC A345 is used to represent the wide character with code 226 ``16#A345#``. 227 This scheme is compatible with use of the full Wide_Character set. 228 229*Upper-Half Coding* 230 .. index:: Upper-Half Coding 231 232 The wide character with encoding ``16#abcd#`` where the upper bit is on 233 (in other words, 'a' is in the range 8-F) is represented as two bytes, 234 ``16#ab#`` and ``16#cd#``. The second byte cannot be a format control 235 character, but is not required to be in the upper half. This method can 236 be also used for shift-JIS or EUC, where the internal coding matches the 237 external coding. 238 239*Shift JIS Coding* 240 .. index:: Shift JIS Coding 241 242 A wide character is represented by a two-character sequence, 243 ``16#ab#`` and 244 ``16#cd#``, with the restrictions described for upper-half encoding as 245 described above. The internal character code is the corresponding JIS 246 character according to the standard algorithm for Shift-JIS 247 conversion. Only characters defined in the JIS code set table can be 248 used with this encoding method. 249 250 251*EUC Coding* 252 .. index:: EUC Coding 253 254 A wide character is represented by a two-character sequence 255 ``16#ab#`` and 256 ``16#cd#``, with both characters being in the upper half. The internal 257 character code is the corresponding JIS character according to the EUC 258 encoding algorithm. Only characters defined in the JIS code set table 259 can be used with this encoding method. 260 261 262*UTF-8 Coding* 263 A wide character is represented using 264 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO 265 10646-1/Am.2. Depending on the character value, the representation 266 is a one, two, or three byte sequence:: 267 268 16#0000#-16#007f#: 2#0xxxxxxx# 269 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx# 270 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx# 271 272 where the ``xxx`` bits correspond to the left-padded bits of the 273 16-bit character value. Note that all lower half ASCII characters 274 are represented as ASCII bytes and all upper half characters and 275 other wide characters are represented as sequences of upper-half 276 (The full UTF-8 scheme allows for encoding 31-bit characters as 277 6-byte sequences, and in the following section on wide wide 278 characters, the use of these sequences is documented). 279 280 281*Brackets Coding* 282 In this encoding, a wide character is represented by the following eight 283 character sequence:: 284 285 [ " a b c d " ] 286 287 where ``a``, ``b``, ``c``, ``d`` are the four hexadecimal 288 characters (using uppercase letters) of the wide character code. For 289 example, ['A345'] is used to represent the wide character with code 290 ``16#A345#``. It is also possible (though not required) to use the 291 Brackets coding for upper half characters. For example, the code 292 ``16#A3#`` can be represented as ``['A3']``. 293 294 This scheme is compatible with use of the full Wide_Character set, 295 and is also the method used for wide character encoding in some standard 296 ACATS (Ada Conformity Assessment Test Suite) test suite distributions. 297 298.. note:: 299 300 Some of these coding schemes do not permit the full use of the 301 Ada character set. For example, neither Shift JIS nor EUC allow the 302 use of the upper half of the Latin-1 set. 303 304.. _Wide_Wide_Character_Encodings: 305 306Wide_Wide_Character Encodings 307----------------------------- 308 309GNAT allows wide wide character codes to appear in character and string 310literals, and also optionally in identifiers, by means of the following 311possible encoding schemes: 312 313*UTF-8 Coding* 314 A wide character is represented using 315 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO 316 10646-1/Am.2. Depending on the character value, the representation 317 of character codes with values greater than 16#FFFF# is a 318 is a four, five, or six byte sequence:: 319 320 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx 321 10xxxxxx 322 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx 323 10xxxxxx 10xxxxxx 324 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx 325 10xxxxxx 10xxxxxx 10xxxxxx 326 327 328 where the ``xxx`` bits correspond to the left-padded bits of the 329 32-bit character value. 330 331*Brackets Coding* 332 In this encoding, a wide wide character is represented by the following ten or 333 twelve byte character sequence:: 334 335 [ " a b c d e f " ] 336 [ " a b c d e f g h " ] 337 338 where ``a-h`` are the six or eight hexadecimal 339 characters (using uppercase letters) of the wide wide character code. For 340 example, ["1F4567"] is used to represent the wide wide character with code 341 ``16#001F_4567#``. 342 343 This scheme is compatible with use of the full Wide_Wide_Character set, 344 and is also the method used for wide wide character encoding in some standard 345 ACATS (Ada Conformity Assessment Test Suite) test suite distributions. 346 347 348.. _File_Naming_Topics_and_Utilities: 349 350File Naming Topics and Utilities 351================================ 352 353GNAT has a default file naming scheme and also provides the user with 354a high degree of control over how the names and extensions of the 355source files correspond to the Ada compilation units that they contain. 356 357 358.. _File_Naming_Rules: 359 360File Naming Rules 361----------------- 362 363The default file name is determined by the name of the unit that the 364file contains. The name is formed by taking the full expanded name of 365the unit and replacing the separating dots with hyphens and using 366lowercase for all letters. 367 368An exception arises if the file name generated by the above rules starts 369with one of the characters 370``a``, ``g``, ``i``, or ``s``, and the second character is a 371minus. In this case, the character tilde is used in place 372of the minus. The reason for this special rule is to avoid clashes with 373the standard names for child units of the packages System, Ada, 374Interfaces, and GNAT, which use the prefixes 375``s-``, ``a-``, ``i-``, and ``g-``, 376respectively. 377 378The file extension is :file:`.ads` for a spec and 379:file:`.adb` for a body. The following table shows some 380examples of these rules. 381 382 ============================ =============================== 383 Source File Ada Compilation Unit 384 ---------------------------- ------------------------------- 385 :file:`main.ads` Main (spec) 386 :file:`main.adb` Main (body) 387 :file:`arith_functions.ads` Arith_Functions (package spec) 388 :file:`arith_functions.adb` Arith_Functions (package body) 389 :file:`func-spec.ads` Func.Spec (child package spec) 390 :file:`func-spec.adb` Func.Spec (child package body) 391 :file:`main-sub.adb` Sub (subunit of Main) 392 :file:`a~bad.adb` A.Bad (child package body) 393 ============================ =============================== 394 395Following these rules can result in excessively long 396file names if corresponding 397unit names are long (for example, if child units or subunits are 398heavily nested). An option is available to shorten such long file names 399(called file name 'krunching'). This may be particularly useful when 400programs being developed with GNAT are to be used on operating systems 401with limited file name lengths. :ref:`Using_gnatkr`. 402 403Of course, no file shortening algorithm can guarantee uniqueness over 404all possible unit names; if file name krunching is used, it is your 405responsibility to ensure no name clashes occur. Alternatively you 406can specify the exact file names that you want used, as described 407in the next section. Finally, if your Ada programs are migrating from a 408compiler with a different naming convention, you can use the gnatchop 409utility to produce source files that follow the GNAT naming conventions. 410(For details see :ref:`Renaming_Files_with_gnatchop`.) 411 412Note: in the case of Windows or Mac OS operating systems, case is not 413significant. So for example on Windows if the canonical name is 414:file:`main-sub.adb`, you can use the file name :file:`Main-Sub.adb` instead. 415However, case is significant for other operating systems, so for example, 416if you want to use other than canonically cased file names on a Unix system, 417you need to follow the procedures described in the next section. 418 419.. _Using_Other_File_Names: 420 421Using Other File Names 422---------------------- 423 424.. index:: File names 425 426In the previous section, we have described the default rules used by 427GNAT to determine the file name in which a given unit resides. It is 428often convenient to follow these default rules, and if you follow them, 429the compiler knows without being explicitly told where to find all 430the files it needs. 431 432.. index:: Source_File_Name pragma 433 434However, in some cases, particularly when a program is imported from 435another Ada compiler environment, it may be more convenient for the 436programmer to specify which file names contain which units. GNAT allows 437arbitrary file names to be used by means of the Source_File_Name pragma. 438The form of this pragma is as shown in the following examples: 439 440.. code-block:: ada 441 442 pragma Source_File_Name (My_Utilities.Stacks, 443 Spec_File_Name => "myutilst_a.ada"); 444 pragma Source_File_name (My_Utilities.Stacks, 445 Body_File_Name => "myutilst.ada"); 446 447As shown in this example, the first argument for the pragma is the unit 448name (in this example a child unit). The second argument has the form 449of a named association. The identifier 450indicates whether the file name is for a spec or a body; 451the file name itself is given by a string literal. 452 453The source file name pragma is a configuration pragma, which means that 454normally it will be placed in the :file:`gnat.adc` 455file used to hold configuration 456pragmas that apply to a complete compilation environment. 457For more details on how the :file:`gnat.adc` file is created and used 458see :ref:`Handling_of_Configuration_Pragmas`. 459 460.. index:: gnat.adc 461 462GNAT allows completely arbitrary file names to be specified using the 463source file name pragma. However, if the file name specified has an 464extension other than :file:`.ads` or :file:`.adb` it is necessary to use 465a special syntax when compiling the file. The name in this case must be 466preceded by the special sequence ``-x`` followed by a space and the name 467of the language, here ``ada``, as in: 468 469.. code-block:: sh 470 471 $ gcc -c -x ada peculiar_file_name.sim 472 473``gnatmake`` handles non-standard file names in the usual manner (the 474non-standard file name for the main program is simply used as the 475argument to gnatmake). Note that if the extension is also non-standard, 476then it must be included in the ``gnatmake`` command, it may not 477be omitted. 478 479.. _Alternative_File_Naming_Schemes: 480 481Alternative File Naming Schemes 482------------------------------- 483 484.. index:: File naming schemes, alternative 485 486.. index:: File names 487 488The previous section described the use of the ``Source_File_Name`` 489pragma to allow arbitrary names to be assigned to individual source files. 490However, this approach requires one pragma for each file, and especially in 491large systems can result in very long :file:`gnat.adc` files, and also create 492a maintenance problem. 493 494.. index:: Source_File_Name pragma 495 496GNAT also provides a facility for specifying systematic file naming schemes 497other than the standard default naming scheme previously described. An 498alternative scheme for naming is specified by the use of 499``Source_File_Name`` pragmas having the following format: 500 501.. code-block:: ada 502 503 pragma Source_File_Name ( 504 Spec_File_Name => FILE_NAME_PATTERN 505 [ , Casing => CASING_SPEC] 506 [ , Dot_Replacement => STRING_LITERAL ] ); 507 508 pragma Source_File_Name ( 509 Body_File_Name => FILE_NAME_PATTERN 510 [ , Casing => CASING_SPEC ] 511 [ , Dot_Replacement => STRING_LITERAL ] ) ; 512 513 pragma Source_File_Name ( 514 Subunit_File_Name => FILE_NAME_PATTERN 515 [ , Casing => CASING_SPEC ] 516 [ , Dot_Replacement => STRING_LITERAL ] ) ; 517 518 FILE_NAME_PATTERN ::= STRING_LITERAL 519 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase 520 521The ``FILE_NAME_PATTERN`` string shows how the file name is constructed. 522It contains a single asterisk character, and the unit name is substituted 523systematically for this asterisk. The optional parameter 524``Casing`` indicates 525whether the unit name is to be all upper-case letters, all lower-case letters, 526or mixed-case. If no 527``Casing`` parameter is used, then the default is all 528lower-case. 529 530The optional ``Dot_Replacement`` string is used to replace any periods 531that occur in subunit or child unit names. If no ``Dot_Replacement`` 532argument is used then separating dots appear unchanged in the resulting 533file name. 534Although the above syntax indicates that the 535``Casing`` argument must appear 536before the ``Dot_Replacement`` argument, but it 537is also permissible to write these arguments in the opposite order. 538 539As indicated, it is possible to specify different naming schemes for 540bodies, specs, and subunits. Quite often the rule for subunits is the 541same as the rule for bodies, in which case, there is no need to give 542a separate ``Subunit_File_Name`` rule, and in this case the 543``Body_File_name`` rule is used for subunits as well. 544 545The separate rule for subunits can also be used to implement the rather 546unusual case of a compilation environment (e.g., a single directory) which 547contains a subunit and a child unit with the same unit name. Although 548both units cannot appear in the same partition, the Ada Reference Manual 549allows (but does not require) the possibility of the two units coexisting 550in the same environment. 551 552The file name translation works in the following steps: 553 554* If there is a specific ``Source_File_Name`` pragma for the given unit, 555 then this is always used, and any general pattern rules are ignored. 556 557* If there is a pattern type ``Source_File_Name`` pragma that applies to 558 the unit, then the resulting file name will be used if the file exists. If 559 more than one pattern matches, the latest one will be tried first, and the 560 first attempt resulting in a reference to a file that exists will be used. 561 562* If no pattern type ``Source_File_Name`` pragma that applies to the unit 563 for which the corresponding file exists, then the standard GNAT default 564 naming rules are used. 565 566As an example of the use of this mechanism, consider a commonly used scheme 567in which file names are all lower case, with separating periods copied 568unchanged to the resulting file name, and specs end with :file:`.1.ada`, and 569bodies end with :file:`.2.ada`. GNAT will follow this scheme if the following 570two pragmas appear: 571 572.. code-block:: ada 573 574 pragma Source_File_Name 575 (Spec_File_Name => ".1.ada"); 576 pragma Source_File_Name 577 (Body_File_Name => ".2.ada"); 578 579The default GNAT scheme is actually implemented by providing the following 580default pragmas internally: 581 582.. code-block:: ada 583 584 pragma Source_File_Name 585 (Spec_File_Name => ".ads", Dot_Replacement => "-"); 586 pragma Source_File_Name 587 (Body_File_Name => ".adb", Dot_Replacement => "-"); 588 589Our final example implements a scheme typically used with one of the 590Ada 83 compilers, where the separator character for subunits was '__' 591(two underscores), specs were identified by adding :file:`_.ADA`, bodies 592by adding :file:`.ADA`, and subunits by 593adding :file:`.SEP`. All file names were 594upper case. Child units were not present of course since this was an 595Ada 83 compiler, but it seems reasonable to extend this scheme to use 596the same double underscore separator for child units. 597 598.. code-block:: ada 599 600 pragma Source_File_Name 601 (Spec_File_Name => "_.ADA", 602 Dot_Replacement => "__", 603 Casing = Uppercase); 604 pragma Source_File_Name 605 (Body_File_Name => ".ADA", 606 Dot_Replacement => "__", 607 Casing = Uppercase); 608 pragma Source_File_Name 609 (Subunit_File_Name => ".SEP", 610 Dot_Replacement => "__", 611 Casing = Uppercase); 612 613 614.. index:: ! gnatname 615 616.. _Handling_Arbitrary_File_Naming_Conventions_with_gnatname: 617 618Handling Arbitrary File Naming Conventions with ``gnatname`` 619------------------------------------------------------------ 620 621.. index:: File Naming Conventions 622 623.. _Arbitrary_File_Naming_Conventions: 624 625Arbitrary File Naming Conventions 626^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 627 628The GNAT compiler must be able to know the source file name of a compilation 629unit. When using the standard GNAT default file naming conventions 630(``.ads`` for specs, ``.adb`` for bodies), the GNAT compiler 631does not need additional information. 632 633When the source file names do not follow the standard GNAT default file naming 634conventions, the GNAT compiler must be given additional information through 635a configuration pragmas file (:ref:`Configuration_Pragmas`) 636or a project file. 637When the non-standard file naming conventions are well-defined, 638a small number of pragmas ``Source_File_Name`` specifying a naming pattern 639(:ref:`Alternative_File_Naming_Schemes`) may be sufficient. However, 640if the file naming conventions are irregular or arbitrary, a number 641of pragma ``Source_File_Name`` for individual compilation units 642must be defined. 643To help maintain the correspondence between compilation unit names and 644source file names within the compiler, 645GNAT provides a tool ``gnatname`` to generate the required pragmas for a 646set of files. 647 648.. _Running_gnatname: 649 650Running ``gnatname`` 651^^^^^^^^^^^^^^^^^^^^ 652 653The usual form of the ``gnatname`` command is: 654 655.. code-block:: sh 656 657 $ gnatname [ switches ] naming_pattern [ naming_patterns ] 658 [--and [ switches ] naming_pattern [ naming_patterns ]] 659 660 661All of the arguments are optional. If invoked without any argument, 662``gnatname`` will display its usage. 663 664When used with at least one naming pattern, ``gnatname`` will attempt to 665find all the compilation units in files that follow at least one of the 666naming patterns. To find these compilation units, 667``gnatname`` will use the GNAT compiler in syntax-check-only mode on all 668regular files. 669 670One or several Naming Patterns may be given as arguments to ``gnatname``. 671Each Naming Pattern is enclosed between double quotes (or single 672quotes on Windows). 673A Naming Pattern is a regular expression similar to the wildcard patterns 674used in file names by the Unix shells or the DOS prompt. 675 676``gnatname`` may be called with several sections of directories/patterns. 677Sections are separated by the switch :switch:`--and`. In each section, there must be 678at least one pattern. If no directory is specified in a section, the current 679directory (or the project directory if :switch:`-P` is used) is implied. 680The options other that the directory switches and the patterns apply globally 681even if they are in different sections. 682 683Examples of Naming Patterns are:: 684 685 "*.[12].ada" 686 "*.ad[sb]*" 687 "body_*" "spec_*" 688 689For a more complete description of the syntax of Naming Patterns, 690see the second kind of regular expressions described in :file:`g-regexp.ads` 691(the 'Glob' regular expressions). 692 693When invoked without the switch :switch:`-P`, ``gnatname`` will create a 694configuration pragmas file :file:`gnat.adc` in the current working directory, 695with pragmas ``Source_File_Name`` for each file that contains a valid Ada 696unit. 697 698.. _Switches_for_gnatname: 699 700Switches for ``gnatname`` 701^^^^^^^^^^^^^^^^^^^^^^^^^ 702 703Switches for ``gnatname`` must precede any specified Naming Pattern. 704 705You may specify any of the following switches to ``gnatname``: 706 707.. index:: --version (gnatname) 708 709:switch:`--version` 710 Display Copyright and version, then exit disregarding all other options. 711 712.. index:: --help (gnatname) 713 714:switch:`--help` 715 If :switch:`--version` was not used, display usage, then exit disregarding 716 all other options. 717 718:switch:`--subdirs={dir}` 719 Real object, library or exec directories are subdirectories <dir> of the 720 specified ones. 721 722:switch:`--no-backup` 723 Do not create a backup copy of an existing project file. 724 725:switch:`--and` 726 Start another section of directories/patterns. 727 728.. index:: -c (gnatname) 729 730:switch:`-c{filename}` 731 Create a configuration pragmas file :file:`filename` (instead of the default 732 :file:`gnat.adc`). 733 There may be zero, one or more space between :switch:`-c` and 734 :file:`filename`. 735 :file:`filename` may include directory information. :file:`filename` must be 736 writable. There may be only one switch :switch:`-c`. 737 When a switch :switch:`-c` is 738 specified, no switch :switch:`-P` may be specified (see below). 739 740.. index:: -d (gnatname) 741 742:switch:`-d{dir}` 743 Look for source files in directory :file:`dir`. There may be zero, one or more 744 spaces between :switch:`-d` and :file:`dir`. 745 :file:`dir` may end with ``/**``, that is it may be of the form 746 ``root_dir/**``. In this case, the directory ``root_dir`` and all of its 747 subdirectories, recursively, have to be searched for sources. 748 When a switch :switch:`-d` 749 is specified, the current working directory will not be searched for source 750 files, unless it is explicitly specified with a :switch:`-d` 751 or :switch:`-D` switch. 752 Several switches :switch:`-d` may be specified. 753 If :file:`dir` is a relative path, it is relative to the directory of 754 the configuration pragmas file specified with switch 755 :switch:`-c`, 756 or to the directory of the project file specified with switch 757 :switch:`-P` or, 758 if neither switch :switch:`-c` 759 nor switch :switch:`-P` are specified, it is relative to the 760 current working directory. The directory 761 specified with switch :switch:`-d` must exist and be readable. 762 763.. index:: -D (gnatname) 764 765:switch:`-D{filename}` 766 Look for source files in all directories listed in text file :file:`filename`. 767 There may be zero, one or more spaces between :switch:`-D` 768 and :file:`filename`. 769 :file:`filename` must be an existing, readable text file. 770 Each nonempty line in :file:`filename` must be a directory. 771 Specifying switch :switch:`-D` is equivalent to specifying as many 772 switches :switch:`-d` as there are nonempty lines in 773 :file:`file`. 774 775:switch:`-eL` 776 Follow symbolic links when processing project files. 777 778 .. index:: -f (gnatname) 779 780:switch:`-f{pattern}` 781 Foreign patterns. Using this switch, it is possible to add sources of languages 782 other than Ada to the list of sources of a project file. 783 It is only useful if a -P switch is used. 784 For example, 785 786 .. code-block:: sh 787 788 gnatname -Pprj -f"*.c" "*.ada" 789 790 will look for Ada units in all files with the :file:`.ada` extension, 791 and will add to the list of file for project :file:`prj.gpr` the C files 792 with extension :file:`.c`. 793 794 .. index:: -h (gnatname) 795 796:switch:`-h` 797 Output usage (help) information. The output is written to :file:`stdout`. 798 799 .. index:: -P (gnatname) 800 801:switch:`-P{proj}` 802 Create or update project file :file:`proj`. There may be zero, one or more space 803 between :switch:`-P` and :file:`proj`. :file:`proj` may include directory 804 information. :file:`proj` must be writable. 805 There may be only one switch :switch:`-P`. 806 When a switch :switch:`-P` is specified, 807 no switch :switch:`-c` may be specified. 808 On all platforms, except on VMS, when ``gnatname`` is invoked for an 809 existing project file <proj>.gpr, a backup copy of the project file is created 810 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first 811 non negative number that makes this backup copy a new file. 812 813 .. index:: -v (gnatname) 814 815:switch:`-v` 816 Verbose mode. Output detailed explanation of behavior to :file:`stdout`. 817 This includes name of the file written, the name of the directories to search 818 and, for each file in those directories whose name matches at least one of 819 the Naming Patterns, an indication of whether the file contains a unit, 820 and if so the name of the unit. 821 822.. index:: -v -v (gnatname) 823 824:switch:`-v -v` 825 Very Verbose mode. In addition to the output produced in verbose mode, 826 for each file in the searched directories whose name matches none of 827 the Naming Patterns, an indication is given that there is no match. 828 829 .. index:: -x (gnatname) 830 831:switch:`-x{pattern}` 832 Excluded patterns. Using this switch, it is possible to exclude some files 833 that would match the name patterns. For example, 834 835 .. code-block:: sh 836 837 gnatname -x "*_nt.ada" "*.ada" 838 839 will look for Ada units in all files with the :file:`.ada` extension, 840 except those whose names end with :file:`_nt.ada`. 841 842 843.. _Examples_of_gnatname_Usage: 844 845Examples of ``gnatname`` Usage 846^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 847 848.. code-block:: sh 849 850 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*" 851 852In this example, the directory :file:`/home/me` must already exist 853and be writable. In addition, the directory 854:file:`/home/me/sources` (specified by 855:switch:`-d sources`) must exist and be readable. 856 857Note the optional spaces after :switch:`-c` and :switch:`-d`. 858 859.. code-block:: sh 860 861 $ gnatname -P/home/me/proj -x "*_nt_body.ada" 862 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*" 863 864Note that several switches :switch:`-d` may be used, 865even in conjunction with one or several switches 866:switch:`-D`. Several Naming Patterns and one excluded pattern 867are used in this example. 868 869 870.. _File_Name_Krunching_with_gnatkr: 871 872File Name Krunching with ``gnatkr`` 873----------------------------------- 874 875.. index:: ! gnatkr 876 877This section discusses the method used by the compiler to shorten 878the default file names chosen for Ada units so that they do not 879exceed the maximum length permitted. It also describes the 880``gnatkr`` utility that can be used to determine the result of 881applying this shortening. 882 883.. _About_gnatkr: 884 885About ``gnatkr`` 886^^^^^^^^^^^^^^^^ 887 888The default file naming rule in GNAT 889is that the file name must be derived from 890the unit name. The exact default rule is as follows: 891 892* Take the unit name and replace all dots by hyphens. 893 894* If such a replacement occurs in the 895 second character position of a name, and the first character is 896 :samp:`a`, :samp:`g`, :samp:`s`, or :samp:`i`, 897 then replace the dot by the character 898 :samp:`~` (tilde) 899 instead of a minus. 900 901 The reason for this exception is to avoid clashes 902 with the standard names for children of System, Ada, Interfaces, 903 and GNAT, which use the prefixes 904 :samp:`s-`, :samp:`a-`, :samp:`i-`, and :samp:`g-`, 905 respectively. 906 907The :switch:`-gnatk{nn}` 908switch of the compiler activates a 'krunching' 909circuit that limits file names to nn characters (where nn is a decimal 910integer). 911 912The ``gnatkr`` utility can be used to determine the krunched name for 913a given file, when krunched to a specified maximum length. 914 915.. _Using_gnatkr: 916 917Using ``gnatkr`` 918^^^^^^^^^^^^^^^^ 919 920The ``gnatkr`` command has the form: 921 922.. code-block:: sh 923 924 $ gnatkr name [ length ] 925 926``name`` is the uncrunched file name, derived from the name of the unit 927in the standard manner described in the previous section (i.e., in particular 928all dots are replaced by hyphens). The file name may or may not have an 929extension (defined as a suffix of the form period followed by arbitrary 930characters other than period). If an extension is present then it will 931be preserved in the output. For example, when krunching :file:`hellofile.ads` 932to eight characters, the result will be hellofil.ads. 933 934Note: for compatibility with previous versions of ``gnatkr`` dots may 935appear in the name instead of hyphens, but the last dot will always be 936taken as the start of an extension. So if ``gnatkr`` is given an argument 937such as :file:`Hello.World.adb` it will be treated exactly as if the first 938period had been a hyphen, and for example krunching to eight characters 939gives the result :file:`hellworl.adb`. 940 941Note that the result is always all lower case. 942Characters of the other case are folded as required. 943 944``length`` represents the length of the krunched name. The default 945when no argument is given is 8 characters. A length of zero stands for 946unlimited, in other words do not chop except for system files where the 947implied crunching length is always eight characters. 948 949The output is the krunched name. The output has an extension only if the 950original argument was a file name with an extension. 951 952.. _Krunching_Method: 953 954Krunching Method 955^^^^^^^^^^^^^^^^ 956 957The initial file name is determined by the name of the unit that the file 958contains. The name is formed by taking the full expanded name of the 959unit and replacing the separating dots with hyphens and 960using lowercase 961for all letters, except that a hyphen in the second character position is 962replaced by a tilde if the first character is 963:samp:`a`, :samp:`i`, :samp:`g`, or :samp:`s`. 964The extension is ``.ads`` for a 965spec and ``.adb`` for a body. 966Krunching does not affect the extension, but the file name is shortened to 967the specified length by following these rules: 968 969* The name is divided into segments separated by hyphens, tildes or 970 underscores and all hyphens, tildes, and underscores are 971 eliminated. If this leaves the name short enough, we are done. 972 973* If the name is too long, the longest segment is located (left-most 974 if there are two of equal length), and shortened by dropping 975 its last character. This is repeated until the name is short enough. 976 977 As an example, consider the krunching of :file:`our-strings-wide_fixed.adb` 978 to fit the name into 8 characters as required by some operating systems:: 979 980 our-strings-wide_fixed 22 981 our strings wide fixed 19 982 our string wide fixed 18 983 our strin wide fixed 17 984 our stri wide fixed 16 985 our stri wide fixe 15 986 our str wide fixe 14 987 our str wid fixe 13 988 our str wid fix 12 989 ou str wid fix 11 990 ou st wid fix 10 991 ou st wi fix 9 992 ou st wi fi 8 993 Final file name: oustwifi.adb 994 995* The file names for all predefined units are always krunched to eight 996 characters. The krunching of these predefined units uses the following 997 special prefix replacements: 998 999 ===================== ============== 1000 Prefix Replacement 1001 --------------------- -------------- 1002 :file:`ada-` :file:`a-` 1003 :file:`gnat-` :file:`g-` 1004 :file:`interfac es-` :file:`i-` 1005 :file:`system-` :file:`s-` 1006 ===================== ============== 1007 1008 These system files have a hyphen in the second character position. That 1009 is why normal user files replace such a character with a 1010 tilde, to avoid confusion with system file names. 1011 1012 As an example of this special rule, consider 1013 :file:`ada-strings-wide_fixed.adb`, which gets krunched as follows:: 1014 1015 ada-strings-wide_fixed 22 1016 a- strings wide fixed 18 1017 a- string wide fixed 17 1018 a- strin wide fixed 16 1019 a- stri wide fixed 15 1020 a- stri wide fixe 14 1021 a- str wide fixe 13 1022 a- str wid fixe 12 1023 a- str wid fix 11 1024 a- st wid fix 10 1025 a- st wi fix 9 1026 a- st wi fi 8 1027 Final file name: a-stwifi.adb 1028 1029Of course no file shortening algorithm can guarantee uniqueness over all 1030possible unit names, and if file name krunching is used then it is your 1031responsibility to ensure that no name clashes occur. The utility 1032program ``gnatkr`` is supplied for conveniently determining the 1033krunched name of a file. 1034 1035.. _Examples_of_gnatkr_Usage: 1036 1037Examples of ``gnatkr`` Usage 1038^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1039 1040:: 1041 1042 $ gnatkr very_long_unit_name.ads --> velounna.ads 1043 $ gnatkr grandparent-parent-child.ads --> grparchi.ads 1044 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads 1045 $ gnatkr grandparent-parent-child --> grparchi 1046 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads 1047 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads 1048 1049 1050.. _Renaming_Files_with_gnatchop: 1051 1052Renaming Files with ``gnatchop`` 1053-------------------------------- 1054 1055.. index:: ! gnatchop 1056 1057This section discusses how to handle files with multiple units by using 1058the ``gnatchop`` utility. This utility is also useful in renaming 1059files to meet the standard GNAT default file naming conventions. 1060 1061.. _Handling_Files_with_Multiple_Units: 1062 1063Handling Files with Multiple Units 1064^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1065 1066The basic compilation model of GNAT requires that a file submitted to the 1067compiler have only one unit and there be a strict correspondence 1068between the file name and the unit name. 1069 1070The ``gnatchop`` utility allows both of these rules to be relaxed, 1071allowing GNAT to process files which contain multiple compilation units 1072and files with arbitrary file names. ``gnatchop`` 1073reads the specified file and generates one or more output files, 1074containing one unit per file. The unit and the file name correspond, 1075as required by GNAT. 1076 1077If you want to permanently restructure a set of 'foreign' files so that 1078they match the GNAT rules, and do the remaining development using the 1079GNAT structure, you can simply use ``gnatchop`` once, generate the 1080new set of files and work with them from that point on. 1081 1082Alternatively, if you want to keep your files in the 'foreign' format, 1083perhaps to maintain compatibility with some other Ada compilation 1084system, you can set up a procedure where you use ``gnatchop`` each 1085time you compile, regarding the source files that it writes as temporary 1086files that you throw away. 1087 1088Note that if your file containing multiple units starts with a byte order 1089mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop 1090will each start with a copy of this BOM, meaning that they can be compiled 1091automatically in UTF-8 mode without needing to specify an explicit encoding. 1092 1093.. _Operating_gnatchop_in_Compilation_Mode: 1094 1095Operating gnatchop in Compilation Mode 1096^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1097 1098The basic function of ``gnatchop`` is to take a file with multiple units 1099and split it into separate files. The boundary between files is reasonably 1100clear, except for the issue of comments and pragmas. In default mode, the 1101rule is that any pragmas between units belong to the previous unit, except 1102that configuration pragmas always belong to the following unit. Any comments 1103belong to the following unit. These rules 1104almost always result in the right choice of 1105the split point without needing to mark it explicitly and most users will 1106find this default to be what they want. In this default mode it is incorrect to 1107submit a file containing only configuration pragmas, or one that ends in 1108configuration pragmas, to ``gnatchop``. 1109 1110However, using a special option to activate 'compilation mode', 1111``gnatchop`` 1112can perform another function, which is to provide exactly the semantics 1113required by the RM for handling of configuration pragmas in a compilation. 1114In the absence of configuration pragmas (at the main file level), this 1115option has no effect, but it causes such configuration pragmas to be handled 1116in a quite different manner. 1117 1118First, in compilation mode, if ``gnatchop`` is given a file that consists of 1119only configuration pragmas, then this file is appended to the 1120:file:`gnat.adc` file in the current directory. This behavior provides 1121the required behavior described in the RM for the actions to be taken 1122on submitting such a file to the compiler, namely that these pragmas 1123should apply to all subsequent compilations in the same compilation 1124environment. Using GNAT, the current directory, possibly containing a 1125:file:`gnat.adc` file is the representation 1126of a compilation environment. For more information on the 1127:file:`gnat.adc` file, see :ref:`Handling_of_Configuration_Pragmas`. 1128 1129Second, in compilation mode, if ``gnatchop`` 1130is given a file that starts with 1131configuration pragmas, and contains one or more units, then these 1132configuration pragmas are prepended to each of the chopped files. This 1133behavior provides the required behavior described in the RM for the 1134actions to be taken on compiling such a file, namely that the pragmas 1135apply to all units in the compilation, but not to subsequently compiled 1136units. 1137 1138Finally, if configuration pragmas appear between units, they are appended 1139to the previous unit. This results in the previous unit being illegal, 1140since the compiler does not accept configuration pragmas that follow 1141a unit. This provides the required RM behavior that forbids configuration 1142pragmas other than those preceding the first compilation unit of a 1143compilation. 1144 1145For most purposes, ``gnatchop`` will be used in default mode. The 1146compilation mode described above is used only if you need exactly 1147accurate behavior with respect to compilations, and you have files 1148that contain multiple units and configuration pragmas. In this 1149circumstance the use of ``gnatchop`` with the compilation mode 1150switch provides the required behavior, and is for example the mode 1151in which GNAT processes the ACVC tests. 1152 1153 1154.. _Command_Line_for_gnatchop: 1155 1156Command Line for ``gnatchop`` 1157^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1158 1159The ``gnatchop`` command has the form: 1160 1161.. code-block:: sh 1162 1163 $ gnatchop switches file_name [file_name ...] 1164 [directory] 1165 1166The only required argument is the file name of the file to be chopped. 1167There are no restrictions on the form of this file name. The file itself 1168contains one or more Ada units, in normal GNAT format, concatenated 1169together. As shown, more than one file may be presented to be chopped. 1170 1171When run in default mode, ``gnatchop`` generates one output file in 1172the current directory for each unit in each of the files. 1173 1174``directory``, if specified, gives the name of the directory to which 1175the output files will be written. If it is not specified, all files are 1176written to the current directory. 1177 1178For example, given a 1179file called :file:`hellofiles` containing 1180 1181.. code-block:: ada 1182 1183 procedure Hello; 1184 1185 with Ada.Text_IO; use Ada.Text_IO; 1186 procedure Hello is 1187 begin 1188 Put_Line ("Hello"); 1189 end Hello; 1190 1191the command 1192 1193.. code-block:: sh 1194 1195 $ gnatchop hellofiles 1196 1197generates two files in the current directory, one called 1198:file:`hello.ads` containing the single line that is the procedure spec, 1199and the other called :file:`hello.adb` containing the remaining text. The 1200original file is not affected. The generated files can be compiled in 1201the normal manner. 1202 1203When gnatchop is invoked on a file that is empty or that contains only empty 1204lines and/or comments, gnatchop will not fail, but will not produce any 1205new sources. 1206 1207For example, given a 1208file called :file:`toto.txt` containing 1209 1210.. code-block:: ada 1211 1212 -- Just a comment 1213 1214the command 1215 1216.. code-block:: sh 1217 1218 $ gnatchop toto.txt 1219 1220will not produce any new file and will result in the following warnings:: 1221 1222 toto.txt:1:01: warning: empty file, contains no compilation units 1223 no compilation units found 1224 no source files written 1225 1226 1227.. _Switches_for_gnatchop: 1228 1229Switches for ``gnatchop`` 1230^^^^^^^^^^^^^^^^^^^^^^^^^ 1231 1232``gnatchop`` recognizes the following switches: 1233 1234 1235.. index:: --version (gnatchop) 1236 1237:switch:`--version` 1238 Display Copyright and version, then exit disregarding all other options. 1239 1240.. index:: --help (gnatchop) 1241 1242:switch:`--help` 1243 If :switch:`--version` was not used, display usage, then exit disregarding 1244 all other options. 1245 1246.. index:: -c (gnatchop) 1247 1248:switch:`-c` 1249 Causes ``gnatchop`` to operate in compilation mode, in which 1250 configuration pragmas are handled according to strict RM rules. See 1251 previous section for a full description of this mode. 1252 1253:switch:`-gnat{xxx}` 1254 This passes the given :switch:`-gnat{xxx}` switch to ``gnat`` which is 1255 used to parse the given file. Not all *xxx* options make sense, 1256 but for example, the use of :switch:`-gnati2` allows ``gnatchop`` to 1257 process a source file that uses Latin-2 coding for identifiers. 1258 1259:switch:`-h` 1260 Causes ``gnatchop`` to generate a brief help summary to the standard 1261 output file showing usage information. 1262 1263.. index:: -k (gnatchop) 1264 1265:switch:`-k{mm}` 1266 Limit generated file names to the specified number ``mm`` 1267 of characters. 1268 This is useful if the 1269 resulting set of files is required to be interoperable with systems 1270 which limit the length of file names. 1271 No space is allowed between the :switch:`-k` and the numeric value. The numeric 1272 value may be omitted in which case a default of :switch:`-k8`, 1273 suitable for use 1274 with DOS-like file systems, is used. If no :switch:`-k` switch 1275 is present then 1276 there is no limit on the length of file names. 1277 1278.. index:: -p (gnatchop) 1279 1280:switch:`-p` 1281 Causes the file modification time stamp of the input file to be 1282 preserved and used for the time stamp of the output file(s). This may be 1283 useful for preserving coherency of time stamps in an environment where 1284 ``gnatchop`` is used as part of a standard build process. 1285 1286.. index:: -q (gnatchop) 1287 1288:switch:`-q` 1289 Causes output of informational messages indicating the set of generated 1290 files to be suppressed. Warnings and error messages are unaffected. 1291 1292.. index:: -r (gnatchop) 1293.. index:: Source_Reference pragmas 1294 1295:switch:`-r` 1296 Generate ``Source_Reference`` pragmas. Use this switch if the output 1297 files are regarded as temporary and development is to be done in terms 1298 of the original unchopped file. This switch causes 1299 ``Source_Reference`` pragmas to be inserted into each of the 1300 generated files to refers back to the original file name and line number. 1301 The result is that all error messages refer back to the original 1302 unchopped file. 1303 In addition, the debugging information placed into the object file (when 1304 the :switch:`-g` switch of ``gcc`` or ``gnatmake`` is 1305 specified) 1306 also refers back to this original file so that tools like profilers and 1307 debuggers will give information in terms of the original unchopped file. 1308 1309 If the original file to be chopped itself contains 1310 a ``Source_Reference`` 1311 pragma referencing a third file, then gnatchop respects 1312 this pragma, and the generated ``Source_Reference`` pragmas 1313 in the chopped file refer to the original file, with appropriate 1314 line numbers. This is particularly useful when ``gnatchop`` 1315 is used in conjunction with ``gnatprep`` to compile files that 1316 contain preprocessing statements and multiple units. 1317 1318.. index:: -v (gnatchop) 1319 1320:switch:`-v` 1321 Causes ``gnatchop`` to operate in verbose mode. The version 1322 number and copyright notice are output, as well as exact copies of 1323 the gnat1 commands spawned to obtain the chop control information. 1324 1325.. index:: -w (gnatchop) 1326 1327:switch:`-w` 1328 Overwrite existing file names. Normally ``gnatchop`` regards it as a 1329 fatal error if there is already a file with the same name as a 1330 file it would otherwise output, in other words if the files to be 1331 chopped contain duplicated units. This switch bypasses this 1332 check, and causes all but the last instance of such duplicated 1333 units to be skipped. 1334 1335.. index:: --GCC= (gnatchop) 1336 1337:switch:`--GCC={xxxx}` 1338 Specify the path of the GNAT parser to be used. When this switch is used, 1339 no attempt is made to add the prefix to the GNAT parser executable. 1340 1341 1342.. _Examples_of_gnatchop_Usage: 1343 1344Examples of ``gnatchop`` Usage 1345^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1346 1347.. code-block:: sh 1348 1349 $ gnatchop -w hello_s.ada prerelease/files 1350 1351Chops the source file :file:`hello_s.ada`. The output files will be 1352placed in the directory :file:`prerelease/files`, 1353overwriting any 1354files with matching names in that directory (no files in the current 1355directory are modified). 1356 1357.. code-block:: sh 1358 1359 $ gnatchop archive 1360 1361Chops the source file :file:`archive` 1362into the current directory. One 1363useful application of ``gnatchop`` is in sending sets of sources 1364around, for example in email messages. The required sources are simply 1365concatenated (for example, using a Unix ``cat`` 1366command), and then 1367``gnatchop`` is used at the other end to reconstitute the original 1368file names. 1369 1370.. code-block:: sh 1371 1372 $ gnatchop file1 file2 file3 direc 1373 1374Chops all units in files :file:`file1`, :file:`file2`, :file:`file3`, placing 1375the resulting files in the directory :file:`direc`. Note that if any units 1376occur more than once anywhere within this set of files, an error message 1377is generated, and no files are written. To override this check, use the 1378:switch:`-w` switch, 1379in which case the last occurrence in the last file will 1380be the one that is output, and earlier duplicate occurrences for a given 1381unit will be skipped. 1382 1383.. _Configuration_Pragmas: 1384 1385Configuration Pragmas 1386===================== 1387 1388.. index:: Configuration pragmas 1389 1390.. index:: Pragmas, configuration 1391 1392Configuration pragmas include those pragmas described as 1393such in the Ada Reference Manual, as well as 1394implementation-dependent pragmas that are configuration pragmas. 1395See the ``Implementation_Defined_Pragmas`` chapter in the 1396:title:`GNAT_Reference_Manual` for details on these 1397additional GNAT-specific configuration pragmas. 1398Most notably, the pragma ``Source_File_Name``, which allows 1399specifying non-default names for source files, is a configuration 1400pragma. The following is a complete list of configuration pragmas 1401recognized by GNAT:: 1402 1403 Ada_83 1404 Ada_95 1405 Ada_05 1406 Ada_2005 1407 Ada_12 1408 Ada_2012 1409 Allow_Integer_Address 1410 Annotate 1411 Assertion_Policy 1412 Assume_No_Invalid_Values 1413 C_Pass_By_Copy 1414 Check_Float_Overflow 1415 Check_Name 1416 Check_Policy 1417 Compile_Time_Error 1418 Compile_Time_Warning 1419 Compiler_Unit 1420 Compiler_Unit_Warning 1421 Component_Alignment 1422 Convention_Identifier 1423 Debug_Policy 1424 Detect_Blocking 1425 Default_Scalar_Storage_Order 1426 Default_Storage_Pool 1427 Disable_Atomic_Synchronization 1428 Discard_Names 1429 Elaboration_Checks 1430 Eliminate 1431 Enable_Atomic_Synchronization 1432 Extend_System 1433 Extensions_Allowed 1434 External_Name_Casing 1435 Fast_Math 1436 Favor_Top_Level 1437 Ignore_Pragma 1438 Implicit_Packing 1439 Initialize_Scalars 1440 Interrupt_State 1441 License 1442 Locking_Policy 1443 No_Component_Reordering 1444 No_Heap_Finalization 1445 No_Run_Time 1446 No_Strict_Aliasing 1447 Normalize_Scalars 1448 Optimize_Alignment 1449 Overflow_Mode 1450 Overriding_Renamings 1451 Partition_Elaboration_Policy 1452 Persistent_BSS 1453 Polling 1454 Prefix_Exception_Messages 1455 Priority_Specific_Dispatching 1456 Profile 1457 Profile_Warnings 1458 Propagate_Exceptions 1459 Queuing_Policy 1460 Rational 1461 Ravenscar 1462 Rename_Pragma 1463 Restricted_Run_Time 1464 Restrictions 1465 Restrictions_Warnings 1466 Reviewable 1467 Short_Circuit_And_Or 1468 Short_Descriptors 1469 Source_File_Name 1470 Source_File_Name_Project 1471 SPARK_Mode 1472 Style_Checks 1473 Suppress 1474 Suppress_Exception_Locations 1475 Task_Dispatching_Policy 1476 Unevaluated_Use_Of_Old 1477 Universal_Data 1478 Unsuppress 1479 Use_VADS_Size 1480 Validity_Checks 1481 Warning_As_Error 1482 Warnings 1483 Wide_Character_Encoding 1484 1485 1486.. _Handling_of_Configuration_Pragmas: 1487 1488Handling of Configuration Pragmas 1489--------------------------------- 1490 1491Configuration pragmas may either appear at the start of a compilation 1492unit, or they can appear in a configuration pragma file to apply to 1493all compilations performed in a given compilation environment. 1494 1495GNAT also provides the ``gnatchop`` utility to provide an automatic 1496way to handle configuration pragmas following the semantics for 1497compilations (that is, files with multiple units), described in the RM. 1498See :ref:`Operating_gnatchop_in_Compilation_Mode` for details. 1499However, for most purposes, it will be more convenient to edit the 1500:file:`gnat.adc` file that contains configuration pragmas directly, 1501as described in the following section. 1502 1503In the case of ``Restrictions`` pragmas appearing as configuration 1504pragmas in individual compilation units, the exact handling depends on 1505the type of restriction. 1506 1507Restrictions that require partition-wide consistency (like 1508``No_Tasking``) are 1509recognized wherever they appear 1510and can be freely inherited, e.g. from a |withed| unit to the |withing| 1511unit. This makes sense since the binder will in any case insist on seeing 1512consistent use, so any unit not conforming to any restrictions that are 1513anywhere in the partition will be rejected, and you might as well find 1514that out at compile time rather than at bind time. 1515 1516For restrictions that do not require partition-wide consistency, e.g. 1517SPARK or No_Implementation_Attributes, in general the restriction applies 1518only to the unit in which the pragma appears, and not to any other units. 1519 1520The exception is No_Elaboration_Code which always applies to the entire 1521object file from a compilation, i.e. to the body, spec, and all subunits. 1522This restriction can be specified in a configuration pragma file, or it 1523can be on the body and/or the spec (in eithe case it applies to all the 1524relevant units). It can appear on a subunit only if it has previously 1525appeared in the body of spec. 1526 1527 1528.. _The_Configuration_Pragmas_Files: 1529 1530The Configuration Pragmas Files 1531------------------------------- 1532 1533.. index:: gnat.adc 1534 1535In GNAT a compilation environment is defined by the current 1536directory at the time that a compile command is given. This current 1537directory is searched for a file whose name is :file:`gnat.adc`. If 1538this file is present, it is expected to contain one or more 1539configuration pragmas that will be applied to the current compilation. 1540However, if the switch :switch:`-gnatA` is used, :file:`gnat.adc` is not 1541considered. When taken into account, :file:`gnat.adc` is added to the 1542dependencies, so that if :file:`gnat.adc` is modified later, an invocation of 1543``gnatmake`` will recompile the source. 1544 1545Configuration pragmas may be entered into the :file:`gnat.adc` file 1546either by running ``gnatchop`` on a source file that consists only of 1547configuration pragmas, or more conveniently by direct editing of the 1548:file:`gnat.adc` file, which is a standard format source file. 1549 1550Besides :file:`gnat.adc`, additional files containing configuration 1551pragmas may be applied to the current compilation using the switch 1552:switch:`-gnatec={path}` where ``path`` must designate an existing file that 1553contains only configuration pragmas. These configuration pragmas are 1554in addition to those found in :file:`gnat.adc` (provided :file:`gnat.adc` 1555is present and switch :switch:`-gnatA` is not used). 1556 1557It is allowable to specify several switches :switch:`-gnatec=`, all of which 1558will be taken into account. 1559 1560Files containing configuration pragmas specified with switches 1561:switch:`-gnatec=` are added to the dependencies, unless they are 1562temporary files. A file is considered temporary if its name ends in 1563:file:`.tmp` or :file:`.TMP`. Certain tools follow this naming 1564convention because they pass information to ``gcc`` via 1565temporary files that are immediately deleted; it doesn't make sense to 1566depend on a file that no longer exists. Such tools include 1567``gprbuild``, ``gnatmake``, and ``gnatcheck``. 1568 1569If you are using project file, a separate mechanism is provided using 1570project attributes. 1571 1572.. --Comment 1573 See :ref:`Specifying_Configuration_Pragmas` for more details. 1574 1575 1576.. _Generating_Object_Files: 1577 1578Generating Object Files 1579======================= 1580 1581An Ada program consists of a set of source files, and the first step in 1582compiling the program is to generate the corresponding object files. 1583These are generated by compiling a subset of these source files. 1584The files you need to compile are the following: 1585 1586* If a package spec has no body, compile the package spec to produce the 1587 object file for the package. 1588 1589* If a package has both a spec and a body, compile the body to produce the 1590 object file for the package. The source file for the package spec need 1591 not be compiled in this case because there is only one object file, which 1592 contains the code for both the spec and body of the package. 1593 1594* For a subprogram, compile the subprogram body to produce the object file 1595 for the subprogram. The spec, if one is present, is as usual in a 1596 separate file, and need not be compiled. 1597 1598.. index:: Subunits 1599 1600* In the case of subunits, only compile the parent unit. A single object 1601 file is generated for the entire subunit tree, which includes all the 1602 subunits. 1603 1604* Compile child units independently of their parent units 1605 (though, of course, the spec of all the ancestor unit must be present in order 1606 to compile a child unit). 1607 1608 .. index:: Generics 1609 1610* Compile generic units in the same manner as any other units. The object 1611 files in this case are small dummy files that contain at most the 1612 flag used for elaboration checking. This is because GNAT always handles generic 1613 instantiation by means of macro expansion. However, it is still necessary to 1614 compile generic units, for dependency checking and elaboration purposes. 1615 1616The preceding rules describe the set of files that must be compiled to 1617generate the object files for a program. Each object file has the same 1618name as the corresponding source file, except that the extension is 1619:file:`.o` as usual. 1620 1621You may wish to compile other files for the purpose of checking their 1622syntactic and semantic correctness. For example, in the case where a 1623package has a separate spec and body, you would not normally compile the 1624spec. However, it is convenient in practice to compile the spec to make 1625sure it is error-free before compiling clients of this spec, because such 1626compilations will fail if there is an error in the spec. 1627 1628GNAT provides an option for compiling such files purely for the 1629purposes of checking correctness; such compilations are not required as 1630part of the process of building a program. To compile a file in this 1631checking mode, use the :switch:`-gnatc` switch. 1632 1633.. _Source_Dependencies: 1634 1635Source Dependencies 1636=================== 1637 1638A given object file clearly depends on the source file which is compiled 1639to produce it. Here we are using "depends" in the sense of a typical 1640``make`` utility; in other words, an object file depends on a source 1641file if changes to the source file require the object file to be 1642recompiled. 1643In addition to this basic dependency, a given object may depend on 1644additional source files as follows: 1645 1646* If a file being compiled |withs| a unit ``X``, the object file 1647 depends on the file containing the spec of unit ``X``. This includes 1648 files that are |withed| implicitly either because they are parents 1649 of |withed| child units or they are run-time units required by the 1650 language constructs used in a particular unit. 1651 1652* If a file being compiled instantiates a library level generic unit, the 1653 object file depends on both the spec and body files for this generic 1654 unit. 1655 1656* If a file being compiled instantiates a generic unit defined within a 1657 package, the object file depends on the body file for the package as 1658 well as the spec file. 1659 1660.. index:: Inline 1661.. index:: -gnatn switch 1662 1663* If a file being compiled contains a call to a subprogram for which 1664 pragma ``Inline`` applies and inlining is activated with the 1665 :switch:`-gnatn` switch, the object file depends on the file containing the 1666 body of this subprogram as well as on the file containing the spec. Note 1667 that for inlining to actually occur as a result of the use of this switch, 1668 it is necessary to compile in optimizing mode. 1669 1670 .. index:: -gnatN switch 1671 1672 The use of :switch:`-gnatN` activates inlining optimization 1673 that is performed by the front end of the compiler. This inlining does 1674 not require that the code generation be optimized. Like :switch:`-gnatn`, 1675 the use of this switch generates additional dependencies. 1676 1677 When using a gcc-based back end (in practice this means using any version 1678 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of 1679 :switch:`-gnatN` is deprecated, and the use of :switch:`-gnatn` is preferred. 1680 Historically front end inlining was more extensive than the gcc back end 1681 inlining, but that is no longer the case. 1682 1683* If an object file :file:`O` depends on the proper body of a subunit through 1684 inlining or instantiation, it depends on the parent unit of the subunit. 1685 This means that any modification of the parent unit or one of its subunits 1686 affects the compilation of :file:`O`. 1687 1688* The object file for a parent unit depends on all its subunit body files. 1689 1690* The previous two rules meant that for purposes of computing dependencies and 1691 recompilation, a body and all its subunits are treated as an indivisible whole. 1692 1693 These rules are applied transitively: if unit ``A`` |withs| 1694 unit ``B``, whose elaboration calls an inlined procedure in package 1695 ``C``, the object file for unit ``A`` will depend on the body of 1696 ``C``, in file :file:`c.adb`. 1697 1698 The set of dependent files described by these rules includes all the 1699 files on which the unit is semantically dependent, as dictated by the 1700 Ada language standard. However, it is a superset of what the 1701 standard describes, because it includes generic, inline, and subunit 1702 dependencies. 1703 1704 An object file must be recreated by recompiling the corresponding source 1705 file if any of the source files on which it depends are modified. For 1706 example, if the ``make`` utility is used to control compilation, 1707 the rule for an Ada object file must mention all the source files on 1708 which the object file depends, according to the above definition. 1709 The determination of the necessary 1710 recompilations is done automatically when one uses ``gnatmake``. 1711 1712.. _The_Ada_Library_Information_Files: 1713 1714The Ada Library Information Files 1715================================= 1716 1717.. index:: Ada Library Information files 1718 1719.. index:: ALI files 1720 1721Each compilation actually generates two output files. The first of these 1722is the normal object file that has a :file:`.o` extension. The second is a 1723text file containing full dependency information. It has the same 1724name as the source file, but an :file:`.ali` extension. 1725This file is known as the Ada Library Information (:file:`ALI`) file. 1726The following information is contained in the :file:`ALI` file. 1727 1728* Version information (indicates which version of GNAT was used to compile 1729 the unit(s) in question) 1730 1731* Main program information (including priority and time slice settings, 1732 as well as the wide character encoding used during compilation). 1733 1734* List of arguments used in the ``gcc`` command for the compilation 1735 1736* Attributes of the unit, including configuration pragmas used, an indication 1737 of whether the compilation was successful, exception model used etc. 1738 1739* A list of relevant restrictions applying to the unit (used for consistency) 1740 checking. 1741 1742* Categorization information (e.g., use of pragma ``Pure``). 1743 1744* Information on all |withed| units, including presence of 1745 ``Elaborate`` or ``Elaborate_All`` pragmas. 1746 1747* Information from any ``Linker_Options`` pragmas used in the unit 1748 1749* Information on the use of ``Body_Version`` or ``Version`` 1750 attributes in the unit. 1751 1752* Dependency information. This is a list of files, together with 1753 time stamp and checksum information. These are files on which 1754 the unit depends in the sense that recompilation is required 1755 if any of these units are modified. 1756 1757* Cross-reference data. Contains information on all entities referenced 1758 in the unit. Used by tools like ``gnatxref`` and ``gnatfind`` to 1759 provide cross-reference information. 1760 1761For a full detailed description of the format of the :file:`ALI` file, 1762see the source of the body of unit ``Lib.Writ``, contained in file 1763:file:`lib-writ.adb` in the GNAT compiler sources. 1764 1765 1766.. _Binding_an_Ada_Program: 1767 1768Binding an Ada Program 1769====================== 1770 1771When using languages such as C and C++, once the source files have been 1772compiled the only remaining step in building an executable program 1773is linking the object modules together. This means that it is possible to 1774link an inconsistent version of a program, in which two units have 1775included different versions of the same header. 1776 1777The rules of Ada do not permit such an inconsistent program to be built. 1778For example, if two clients have different versions of the same package, 1779it is illegal to build a program containing these two clients. 1780These rules are enforced by the GNAT binder, which also determines an 1781elaboration order consistent with the Ada rules. 1782 1783The GNAT binder is run after all the object files for a program have 1784been created. It is given the name of the main program unit, and from 1785this it determines the set of units required by the program, by reading the 1786corresponding ALI files. It generates error messages if the program is 1787inconsistent or if no valid order of elaboration exists. 1788 1789If no errors are detected, the binder produces a main program, in Ada by 1790default, that contains calls to the elaboration procedures of those 1791compilation unit that require them, followed by 1792a call to the main program. This Ada program is compiled to generate the 1793object file for the main program. The name of 1794the Ada file is :file:`b~xxx`.adb` (with the corresponding spec 1795:file:`b~xxx`.ads`) where ``xxx`` is the name of the 1796main program unit. 1797 1798Finally, the linker is used to build the resulting executable program, 1799using the object from the main program from the bind step as well as the 1800object files for the Ada units of the program. 1801 1802 1803.. _GNAT_and_Libraries: 1804 1805GNAT and Libraries 1806================== 1807 1808.. index:: Library building and using 1809 1810This section describes how to build and use libraries with GNAT, and also shows 1811how to recompile the GNAT run-time library. You should be familiar with the 1812Project Manager facility (see the *GNAT_Project_Manager* chapter of the 1813*GPRbuild User's Guide*) before reading this chapter. 1814 1815.. _Introduction_to_Libraries_in_GNAT: 1816 1817Introduction to Libraries in GNAT 1818--------------------------------- 1819 1820A library is, conceptually, a collection of objects which does not have its 1821own main thread of execution, but rather provides certain services to the 1822applications that use it. A library can be either statically linked with the 1823application, in which case its code is directly included in the application, 1824or, on platforms that support it, be dynamically linked, in which case 1825its code is shared by all applications making use of this library. 1826 1827GNAT supports both types of libraries. 1828In the static case, the compiled code can be provided in different ways. The 1829simplest approach is to provide directly the set of objects resulting from 1830compilation of the library source files. Alternatively, you can group the 1831objects into an archive using whatever commands are provided by the operating 1832system. For the latter case, the objects are grouped into a shared library. 1833 1834In the GNAT environment, a library has three types of components: 1835 1836* Source files, 1837 1838* :file:`ALI` files (see :ref:`The_Ada_Library_Information_Files`), and 1839 1840* Object files, an archive or a shared library. 1841 1842A GNAT library may expose all its source files, which is useful for 1843documentation purposes. Alternatively, it may expose only the units needed by 1844an external user to make use of the library. That is to say, the specs 1845reflecting the library services along with all the units needed to compile 1846those specs, which can include generic bodies or any body implementing an 1847inlined routine. In the case of *stand-alone libraries* those exposed 1848units are called *interface units* (:ref:`Stand-alone_Ada_Libraries`). 1849 1850All compilation units comprising an application, including those in a library, 1851need to be elaborated in an order partially defined by Ada's semantics. GNAT 1852computes the elaboration order from the :file:`ALI` files and this is why they 1853constitute a mandatory part of GNAT libraries. 1854*Stand-alone libraries* are the exception to this rule because a specific 1855library elaboration routine is produced independently of the application(s) 1856using the library. 1857 1858.. _General_Ada_Libraries: 1859 1860General Ada Libraries 1861--------------------- 1862 1863 1864.. _Building_a_library: 1865 1866Building a library 1867^^^^^^^^^^^^^^^^^^ 1868 1869The easiest way to build a library is to use the Project Manager, 1870which supports a special type of project called a *Library Project* 1871(see the *Library Projects* section in the *GNAT Project Manager* 1872chapter of the *GPRbuild User's Guide*). 1873 1874A project is considered a library project, when two project-level attributes 1875are defined in it: ``Library_Name`` and ``Library_Dir``. In order to 1876control different aspects of library configuration, additional optional 1877project-level attributes can be specified: 1878 1879* ``Library_Kind`` 1880 This attribute controls whether the library is to be static or dynamic 1881 1882 1883* ``Library_Version`` 1884 This attribute specifies the library version; this value is used 1885 during dynamic linking of shared libraries to determine if the currently 1886 installed versions of the binaries are compatible. 1887 1888* ``Library_Options`` 1889 1890* ``Library_GCC`` 1891 These attributes specify additional low-level options to be used during 1892 library generation, and redefine the actual application used to generate 1893 library. 1894 1895The GNAT Project Manager takes full care of the library maintenance task, 1896including recompilation of the source files for which objects do not exist 1897or are not up to date, assembly of the library archive, and installation of 1898the library (i.e., copying associated source, object and :file:`ALI` files 1899to the specified location). 1900 1901Here is a simple library project file: 1902 1903.. code-block:: gpr 1904 1905 project My_Lib is 1906 for Source_Dirs use ("src1", "src2"); 1907 for Object_Dir use "obj"; 1908 for Library_Name use "mylib"; 1909 for Library_Dir use "lib"; 1910 for Library_Kind use "dynamic"; 1911 end My_lib; 1912 1913and the compilation command to build and install the library: 1914 1915.. code-block:: sh 1916 1917 $ gnatmake -Pmy_lib 1918 1919It is not entirely trivial to perform manually all the steps required to 1920produce a library. We recommend that you use the GNAT Project Manager 1921for this task. In special cases where this is not desired, the necessary 1922steps are discussed below. 1923 1924There are various possibilities for compiling the units that make up the 1925library: for example with a Makefile (:ref:`Using_the_GNU_make_Utility`) or 1926with a conventional script. For simple libraries, it is also possible to create 1927a dummy main program which depends upon all the packages that comprise the 1928interface of the library. This dummy main program can then be given to 1929``gnatmake``, which will ensure that all necessary objects are built. 1930 1931After this task is accomplished, you should follow the standard procedure 1932of the underlying operating system to produce the static or shared library. 1933 1934Here is an example of such a dummy program: 1935 1936.. code-block:: ada 1937 1938 with My_Lib.Service1; 1939 with My_Lib.Service2; 1940 with My_Lib.Service3; 1941 procedure My_Lib_Dummy is 1942 begin 1943 null; 1944 end; 1945 1946Here are the generic commands that will build an archive or a shared library. 1947 1948.. code-block:: sh 1949 1950 # compiling the library 1951 $ gnatmake -c my_lib_dummy.adb 1952 1953 # we don't need the dummy object itself 1954 $ rm my_lib_dummy.o my_lib_dummy.ali 1955 1956 # create an archive with the remaining objects 1957 $ ar rc libmy_lib.a *.o 1958 # some systems may require "ranlib" to be run as well 1959 1960 # or create a shared library 1961 $ gcc -shared -o libmy_lib.so *.o 1962 # some systems may require the code to have been compiled with -fPIC 1963 1964 # remove the object files that are now in the library 1965 $ rm *.o 1966 1967 # Make the ALI files read-only so that gnatmake will not try to 1968 # regenerate the objects that are in the library 1969 $ chmod -w *.ali 1970 1971Please note that the library must have a name of the form :file:`lib{xxx}.a` 1972or :file:`lib{xxx}.so` (or :file:`lib{xxx}.dll` on Windows) in order to 1973be accessed by the directive :switch:`-l{xxx}` at link time. 1974 1975.. _Installing_a_library: 1976 1977Installing a library 1978^^^^^^^^^^^^^^^^^^^^ 1979 1980.. index:: ADA_PROJECT_PATH 1981.. index:: GPR_PROJECT_PATH 1982 1983If you use project files, library installation is part of the library build 1984process (see the *Installing a Library with Project Files* section of the 1985*GNAT Project Manager* chapter of the *GPRbuild User's Guide*). 1986 1987When project files are not an option, it is also possible, but not recommended, 1988to install the library so that the sources needed to use the library are on the 1989Ada source path and the ALI files & libraries be on the Ada Object path (see 1990:ref:`Search_Paths_and_the_Run-Time_Library_RTL`. Alternatively, the system 1991administrator can place general-purpose libraries in the default compiler 1992paths, by specifying the libraries' location in the configuration files 1993:file:`ada_source_path` and :file:`ada_object_path`. These configuration files 1994must be located in the GNAT installation tree at the same place as the gcc spec 1995file. The location of the gcc spec file can be determined as follows: 1996 1997.. code-block:: sh 1998 1999 $ gcc -v 2000 2001 2002The configuration files mentioned above have a simple format: each line 2003must contain one unique directory name. 2004Those names are added to the corresponding path 2005in their order of appearance in the file. The names can be either absolute 2006or relative; in the latter case, they are relative to where theses files 2007are located. 2008 2009The files :file:`ada_source_path` and :file:`ada_object_path` might not be 2010present in a 2011GNAT installation, in which case, GNAT will look for its run-time library in 2012the directories :file:`adainclude` (for the sources) and :file:`adalib` (for the 2013objects and :file:`ALI` files). When the files exist, the compiler does not 2014look in :file:`adainclude` and :file:`adalib`, and thus the 2015:file:`ada_source_path` file 2016must contain the location for the GNAT run-time sources (which can simply 2017be :file:`adainclude`). In the same way, the :file:`ada_object_path` file must 2018contain the location for the GNAT run-time objects (which can simply 2019be :file:`adalib`). 2020 2021You can also specify a new default path to the run-time library at compilation 2022time with the switch :switch:`--RTS=rts-path`. You can thus choose / change 2023the run-time library you want your program to be compiled with. This switch is 2024recognized by ``gcc``, ``gnatmake``, ``gnatbind``, 2025``gnatls``, ``gnatfind`` and ``gnatxref``. 2026 2027It is possible to install a library before or after the standard GNAT 2028library, by reordering the lines in the configuration files. In general, a 2029library must be installed before the GNAT library if it redefines 2030any part of it. 2031 2032.. _Using_a_library: 2033 2034Using a library 2035^^^^^^^^^^^^^^^ 2036 2037Once again, the project facility greatly simplifies the use of 2038libraries. In this context, using a library is just a matter of adding a 2039|with| clause in the user project. For instance, to make use of the 2040library ``My_Lib`` shown in examples in earlier sections, you can 2041write: 2042 2043.. code-block:: gpr 2044 2045 with "my_lib"; 2046 project My_Proj is 2047 ... 2048 end My_Proj; 2049 2050Even if you have a third-party, non-Ada library, you can still use GNAT's 2051Project Manager facility to provide a wrapper for it. For example, the 2052following project, when |withed| by your main project, will link with the 2053third-party library :file:`liba.a`: 2054 2055.. code-block:: gpr 2056 2057 project Liba is 2058 for Externally_Built use "true"; 2059 for Source_Files use (); 2060 for Library_Dir use "lib"; 2061 for Library_Name use "a"; 2062 for Library_Kind use "static"; 2063 end Liba; 2064 2065This is an alternative to the use of ``pragma Linker_Options``. It is 2066especially interesting in the context of systems with several interdependent 2067static libraries where finding a proper linker order is not easy and best be 2068left to the tools having visibility over project dependence information. 2069 2070In order to use an Ada library manually, you need to make sure that this 2071library is on both your source and object path 2072(see :ref:`Search_Paths_and_the_Run-Time_Library_RTL` 2073and :ref:`Search_Paths_for_gnatbind`). Furthermore, when the objects are grouped 2074in an archive or a shared library, you need to specify the desired 2075library at link time. 2076 2077For example, you can use the library :file:`mylib` installed in 2078:file:`/dir/my_lib_src` and :file:`/dir/my_lib_obj` with the following commands: 2079 2080.. code-block:: sh 2081 2082 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\ 2083 -largs -lmy_lib 2084 2085This can be expressed more simply: 2086 2087.. code-block:: sh 2088 2089 $ gnatmake my_appl 2090 2091when the following conditions are met: 2092 2093* :file:`/dir/my_lib_src` has been added by the user to the environment 2094 variable :envvar:`ADA_INCLUDE_PATH`, or by the administrator to the file 2095 :file:`ada_source_path` 2096 2097* :file:`/dir/my_lib_obj` has been added by the user to the environment 2098 variable :envvar:`ADA_OBJECTS_PATH`, or by the administrator to the file 2099 :file:`ada_object_path` 2100 2101* a pragma ``Linker_Options`` has been added to one of the sources. 2102 For example: 2103 2104 .. code-block:: ada 2105 2106 pragma Linker_Options ("-lmy_lib"); 2107 2108Note that you may also load a library dynamically at 2109run time given its filename, as illustrated in the GNAT :file:`plugins` example 2110in the directory :file:`share/examples/gnat/plugins` within the GNAT 2111install area. 2112 2113.. _Stand-alone_Ada_Libraries: 2114 2115Stand-alone Ada Libraries 2116------------------------- 2117 2118.. index:: ! Stand-alone libraries 2119 2120.. _Introduction_to_Stand-alone_Libraries: 2121 2122Introduction to Stand-alone Libraries 2123^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2124 2125A Stand-alone Library (abbreviated 'SAL') is a library that contains the 2126necessary code to 2127elaborate the Ada units that are included in the library. In contrast with 2128an ordinary library, which consists of all sources, objects and :file:`ALI` 2129files of the 2130library, a SAL may specify a restricted subset of compilation units 2131to serve as a library interface. In this case, the fully 2132self-sufficient set of files will normally consist of an objects 2133archive, the sources of interface units' specs, and the :file:`ALI` 2134files of interface units. 2135If an interface spec contains a generic unit or an inlined subprogram, 2136the body's 2137source must also be provided; if the units that must be provided in the source 2138form depend on other units, the source and :file:`ALI` files of those must 2139also be provided. 2140 2141The main purpose of a SAL is to minimize the recompilation overhead of client 2142applications when a new version of the library is installed. Specifically, 2143if the interface sources have not changed, client applications do not need to 2144be recompiled. If, furthermore, a SAL is provided in the shared form and its 2145version, controlled by ``Library_Version`` attribute, is not changed, 2146then the clients do not need to be relinked. 2147 2148SALs also allow the library providers to minimize the amount of library source 2149text exposed to the clients. Such 'information hiding' might be useful or 2150necessary for various reasons. 2151 2152Stand-alone libraries are also well suited to be used in an executable whose 2153main routine is not written in Ada. 2154 2155.. _Building_a_Stand-alone_Library: 2156 2157Building a Stand-alone Library 2158^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2159 2160GNAT's Project facility provides a simple way of building and installing 2161stand-alone libraries; see the *Stand-alone Library Projects* section 2162in the *GNAT Project Manager* chapter of the *GPRbuild User's Guide*. 2163To be a Stand-alone Library Project, in addition to the two attributes 2164that make a project a Library Project (``Library_Name`` and 2165``Library_Dir``; see the *Library Projects* section in the 2166*GNAT Project Manager* chapter of the *GPRbuild User's Guide*), 2167the attribute ``Library_Interface`` must be defined. For example: 2168 2169.. code-block:: gpr 2170 2171 for Library_Dir use "lib_dir"; 2172 for Library_Name use "dummy"; 2173 for Library_Interface use ("int1", "int1.child"); 2174 2175Attribute ``Library_Interface`` has a non-empty string list value, 2176each string in the list designating a unit contained in an immediate source 2177of the project file. 2178 2179When a Stand-alone Library is built, first the binder is invoked to build 2180a package whose name depends on the library name 2181(:file:`b~dummy.ads/b` in the example above). 2182This binder-generated package includes initialization and 2183finalization procedures whose 2184names depend on the library name (``dummyinit`` and ``dummyfinal`` 2185in the example 2186above). The object corresponding to this package is included in the library. 2187 2188You must ensure timely (e.g., prior to any use of interfaces in the SAL) 2189calling of these procedures if a static SAL is built, or if a shared SAL 2190is built 2191with the project-level attribute ``Library_Auto_Init`` set to 2192``"false"``. 2193 2194For a Stand-Alone Library, only the :file:`ALI` files of the Interface Units 2195(those that are listed in attribute ``Library_Interface``) are copied to 2196the Library Directory. As a consequence, only the Interface Units may be 2197imported from Ada units outside of the library. If other units are imported, 2198the binding phase will fail. 2199 2200It is also possible to build an encapsulated library where not only 2201the code to elaborate and finalize the library is embedded but also 2202ensuring that the library is linked only against static 2203libraries. So an encapsulated library only depends on system 2204libraries, all other code, including the GNAT runtime, is embedded. To 2205build an encapsulated library the attribute 2206``Library_Standalone`` must be set to ``encapsulated``: 2207 2208.. code-block:: gpr 2209 2210 for Library_Dir use "lib_dir"; 2211 for Library_Name use "dummy"; 2212 for Library_Kind use "dynamic"; 2213 for Library_Interface use ("int1", "int1.child"); 2214 for Library_Standalone use "encapsulated"; 2215 2216The default value for this attribute is ``standard`` in which case 2217a stand-alone library is built. 2218 2219The attribute ``Library_Src_Dir`` may be specified for a 2220Stand-Alone Library. ``Library_Src_Dir`` is a simple attribute that has a 2221single string value. Its value must be the path (absolute or relative to the 2222project directory) of an existing directory. This directory cannot be the 2223object directory or one of the source directories, but it can be the same as 2224the library directory. The sources of the Interface 2225Units of the library that are needed by an Ada client of the library will be 2226copied to the designated directory, called the Interface Copy directory. 2227These sources include the specs of the Interface Units, but they may also 2228include bodies and subunits, when pragmas ``Inline`` or ``Inline_Always`` 2229are used, or when there is a generic unit in the spec. Before the sources 2230are copied to the Interface Copy directory, an attempt is made to delete all 2231files in the Interface Copy directory. 2232 2233Building stand-alone libraries by hand is somewhat tedious, but for those 2234occasions when it is necessary here are the steps that you need to perform: 2235 2236* Compile all library sources. 2237 2238* Invoke the binder with the switch :switch:`-n` (No Ada main program), 2239 with all the :file:`ALI` files of the interfaces, and 2240 with the switch :switch:`-L` to give specific names to the ``init`` 2241 and ``final`` procedures. For example: 2242 2243 .. code-block:: sh 2244 2245 $ gnatbind -n int1.ali int2.ali -Lsal1 2246 2247* Compile the binder generated file: 2248 2249 .. code-block:: sh 2250 2251 $ gcc -c b~int2.adb 2252 2253* Link the dynamic library with all the necessary object files, 2254 indicating to the linker the names of the ``init`` (and possibly 2255 ``final``) procedures for automatic initialization (and finalization). 2256 The built library should be placed in a directory different from 2257 the object directory. 2258 2259* Copy the ``ALI`` files of the interface to the library directory, 2260 add in this copy an indication that it is an interface to a SAL 2261 (i.e., add a word ``SL`` on the line in the :file:`ALI` file that starts 2262 with letter 'P') and make the modified copy of the :file:`ALI` file 2263 read-only. 2264 2265Using SALs is not different from using other libraries 2266(see :ref:`Using_a_library`). 2267 2268.. _Creating_a_Stand-alone_Library_to_be_used_in_a_non-Ada_context: 2269 2270Creating a Stand-alone Library to be used in a non-Ada context 2271^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2272 2273It is easy to adapt the SAL build procedure discussed above for use of a SAL in 2274a non-Ada context. 2275 2276The only extra step required is to ensure that library interface subprograms 2277are compatible with the main program, by means of ``pragma Export`` 2278or ``pragma Convention``. 2279 2280Here is an example of simple library interface for use with C main program: 2281 2282.. code-block:: ada 2283 2284 package My_Package is 2285 2286 procedure Do_Something; 2287 pragma Export (C, Do_Something, "do_something"); 2288 2289 procedure Do_Something_Else; 2290 pragma Export (C, Do_Something_Else, "do_something_else"); 2291 2292 end My_Package; 2293 2294On the foreign language side, you must provide a 'foreign' view of the 2295library interface; remember that it should contain elaboration routines in 2296addition to interface subprograms. 2297 2298The example below shows the content of :file:`mylib_interface.h` (note 2299that there is no rule for the naming of this file, any name can be used) 2300 2301.. code-block:: c 2302 2303 /* the library elaboration procedure */ 2304 extern void mylibinit (void); 2305 2306 /* the library finalization procedure */ 2307 extern void mylibfinal (void); 2308 2309 /* the interface exported by the library */ 2310 extern void do_something (void); 2311 extern void do_something_else (void); 2312 2313Libraries built as explained above can be used from any program, provided 2314that the elaboration procedures (named ``mylibinit`` in the previous 2315example) are called before the library services are used. Any number of 2316libraries can be used simultaneously, as long as the elaboration 2317procedure of each library is called. 2318 2319Below is an example of a C program that uses the ``mylib`` library. 2320 2321.. code-block:: c 2322 2323 #include "mylib_interface.h" 2324 2325 int 2326 main (void) 2327 { 2328 /* First, elaborate the library before using it */ 2329 mylibinit (); 2330 2331 /* Main program, using the library exported entities */ 2332 do_something (); 2333 do_something_else (); 2334 2335 /* Library finalization at the end of the program */ 2336 mylibfinal (); 2337 return 0; 2338 } 2339 2340Note that invoking any library finalization procedure generated by 2341``gnatbind`` shuts down the Ada run-time environment. 2342Consequently, the 2343finalization of all Ada libraries must be performed at the end of the program. 2344No call to these libraries or to the Ada run-time library should be made 2345after the finalization phase. 2346 2347Note also that special care must be taken with multi-tasks 2348applications. The initialization and finalization routines are not 2349protected against concurrent access. If such requirement is needed it 2350must be ensured at the application level using a specific operating 2351system services like a mutex or a critical-section. 2352 2353.. _Restrictions_in_Stand-alone_Libraries: 2354 2355Restrictions in Stand-alone Libraries 2356^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2357 2358The pragmas listed below should be used with caution inside libraries, 2359as they can create incompatibilities with other Ada libraries: 2360 2361* pragma ``Locking_Policy`` 2362* pragma ``Partition_Elaboration_Policy`` 2363* pragma ``Queuing_Policy`` 2364* pragma ``Task_Dispatching_Policy`` 2365* pragma ``Unreserve_All_Interrupts`` 2366 2367When using a library that contains such pragmas, the user must make sure 2368that all libraries use the same pragmas with the same values. Otherwise, 2369``Program_Error`` will 2370be raised during the elaboration of the conflicting 2371libraries. The usage of these pragmas and its consequences for the user 2372should therefore be well documented. 2373 2374Similarly, the traceback in the exception occurrence mechanism should be 2375enabled or disabled in a consistent manner across all libraries. 2376Otherwise, Program_Error will be raised during the elaboration of the 2377conflicting libraries. 2378 2379If the ``Version`` or ``Body_Version`` 2380attributes are used inside a library, then you need to 2381perform a ``gnatbind`` step that specifies all :file:`ALI` files in all 2382libraries, so that version identifiers can be properly computed. 2383In practice these attributes are rarely used, so this is unlikely 2384to be a consideration. 2385 2386.. _Rebuilding_the_GNAT_Run-Time_Library: 2387 2388Rebuilding the GNAT Run-Time Library 2389------------------------------------ 2390 2391.. index:: GNAT Run-Time Library, rebuilding 2392.. index:: Building the GNAT Run-Time Library 2393.. index:: Rebuilding the GNAT Run-Time Library 2394.. index:: Run-Time Library, rebuilding 2395 2396It may be useful to recompile the GNAT library in various contexts, the 2397most important one being the use of partition-wide configuration pragmas 2398such as ``Normalize_Scalars``. A special Makefile called 2399:file:`Makefile.adalib` is provided to that effect and can be found in 2400the directory containing the GNAT library. The location of this 2401directory depends on the way the GNAT environment has been installed and can 2402be determined by means of the command: 2403 2404.. code-block:: sh 2405 2406 $ gnatls -v 2407 2408The last entry in the object search path usually contains the 2409gnat library. This Makefile contains its own documentation and in 2410particular the set of instructions needed to rebuild a new library and 2411to use it. 2412 2413 2414.. index:: ! Conditional compilation 2415 2416.. _Conditional_Compilation: 2417 2418Conditional Compilation 2419======================= 2420 2421This section presents some guidelines for modeling conditional compilation in Ada and describes the 2422gnatprep preprocessor utility. 2423 2424.. index:: ! Conditional compilation 2425 2426.. _Modeling_Conditional_Compilation_in_Ada: 2427 2428Modeling Conditional Compilation in Ada 2429--------------------------------------- 2430 2431It is often necessary to arrange for a single source program 2432to serve multiple purposes, where it is compiled in different 2433ways to achieve these different goals. Some examples of the 2434need for this feature are 2435 2436* Adapting a program to a different hardware environment 2437* Adapting a program to a different target architecture 2438* Turning debugging features on and off 2439* Arranging for a program to compile with different compilers 2440 2441In C, or C++, the typical approach would be to use the preprocessor 2442that is defined as part of the language. The Ada language does not 2443contain such a feature. This is not an oversight, but rather a very 2444deliberate design decision, based on the experience that overuse of 2445the preprocessing features in C and C++ can result in programs that 2446are extremely difficult to maintain. For example, if we have ten 2447switches that can be on or off, this means that there are a thousand 2448separate programs, any one of which might not even be syntactically 2449correct, and even if syntactically correct, the resulting program 2450might not work correctly. Testing all combinations can quickly become 2451impossible. 2452 2453Nevertheless, the need to tailor programs certainly exists, and in 2454this section we will discuss how this can 2455be achieved using Ada in general, and GNAT in particular. 2456 2457.. _Use_of_Boolean_Constants: 2458 2459Use of Boolean Constants 2460^^^^^^^^^^^^^^^^^^^^^^^^ 2461 2462In the case where the difference is simply which code 2463sequence is executed, the cleanest solution is to use Boolean 2464constants to control which code is executed. 2465 2466.. code-block:: ada 2467 2468 FP_Initialize_Required : constant Boolean := True; 2469 ... 2470 if FP_Initialize_Required then 2471 ... 2472 end if; 2473 2474Not only will the code inside the ``if`` statement not be executed if 2475the constant Boolean is ``False``, but it will also be completely 2476deleted from the program. 2477However, the code is only deleted after the ``if`` statement 2478has been checked for syntactic and semantic correctness. 2479(In contrast, with preprocessors the code is deleted before the 2480compiler ever gets to see it, so it is not checked until the switch 2481is turned on.) 2482 2483.. index:: Preprocessors (contrasted with conditional compilation) 2484 2485Typically the Boolean constants will be in a separate package, 2486something like: 2487 2488.. code-block:: ada 2489 2490 package Config is 2491 FP_Initialize_Required : constant Boolean := True; 2492 Reset_Available : constant Boolean := False; 2493 ... 2494 end Config; 2495 2496The ``Config`` package exists in multiple forms for the various targets, 2497with an appropriate script selecting the version of ``Config`` needed. 2498Then any other unit requiring conditional compilation can do a |with| 2499of ``Config`` to make the constants visible. 2500 2501.. _Debugging_-_A_Special_Case: 2502 2503Debugging - A Special Case 2504^^^^^^^^^^^^^^^^^^^^^^^^^^ 2505 2506A common use of conditional code is to execute statements (for example 2507dynamic checks, or output of intermediate results) under control of a 2508debug switch, so that the debugging behavior can be turned on and off. 2509This can be done using a Boolean constant to control whether the code 2510is active: 2511 2512.. code-block:: ada 2513 2514 if Debugging then 2515 Put_Line ("got to the first stage!"); 2516 end if; 2517 2518or 2519 2520.. code-block:: ada 2521 2522 if Debugging and then Temperature > 999.0 then 2523 raise Temperature_Crazy; 2524 end if; 2525 2526.. index:: pragma Assert 2527 2528Since this is a common case, there are special features to deal with 2529this in a convenient manner. For the case of tests, Ada 2005 has added 2530a pragma ``Assert`` that can be used for such tests. This pragma is modeled 2531on the ``Assert`` pragma that has always been available in GNAT, so this 2532feature may be used with GNAT even if you are not using Ada 2005 features. 2533The use of pragma ``Assert`` is described in the 2534:title:`GNAT_Reference_Manual`, but as an 2535example, the last test could be written: 2536 2537.. code-block:: ada 2538 2539 pragma Assert (Temperature <= 999.0, "Temperature Crazy"); 2540 2541or simply 2542 2543.. code-block:: ada 2544 2545 pragma Assert (Temperature <= 999.0); 2546 2547In both cases, if assertions are active and the temperature is excessive, 2548the exception ``Assert_Failure`` will be raised, with the given string in 2549the first case or a string indicating the location of the pragma in the second 2550case used as the exception message. 2551 2552.. index:: pragma Assertion_Policy 2553 2554You can turn assertions on and off by using the ``Assertion_Policy`` 2555pragma. 2556 2557.. index:: -gnata switch 2558 2559This is an Ada 2005 pragma which is implemented in all modes by 2560GNAT. Alternatively, you can use the :switch:`-gnata` switch 2561to enable assertions from the command line, which applies to 2562all versions of Ada. 2563 2564.. index:: pragma Debug 2565 2566For the example above with the ``Put_Line``, the GNAT-specific pragma 2567``Debug`` can be used: 2568 2569.. code-block:: ada 2570 2571 pragma Debug (Put_Line ("got to the first stage!")); 2572 2573If debug pragmas are enabled, the argument, which must be of the form of 2574a procedure call, is executed (in this case, ``Put_Line`` will be called). 2575Only one call can be present, but of course a special debugging procedure 2576containing any code you like can be included in the program and then 2577called in a pragma ``Debug`` argument as needed. 2578 2579One advantage of pragma ``Debug`` over the ``if Debugging then`` 2580construct is that pragma ``Debug`` can appear in declarative contexts, 2581such as at the very beginning of a procedure, before local declarations have 2582been elaborated. 2583 2584.. index:: pragma Debug_Policy 2585 2586Debug pragmas are enabled using either the :switch:`-gnata` switch that also 2587controls assertions, or with a separate Debug_Policy pragma. 2588 2589The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used 2590in Ada 95 and Ada 83 programs as well), and is analogous to 2591pragma ``Assertion_Policy`` to control assertions. 2592 2593``Assertion_Policy`` and ``Debug_Policy`` are configuration pragmas, 2594and thus they can appear in :file:`gnat.adc` if you are not using a 2595project file, or in the file designated to contain configuration pragmas 2596in a project file. 2597They then apply to all subsequent compilations. In practice the use of 2598the :switch:`-gnata` switch is often the most convenient method of controlling 2599the status of these pragmas. 2600 2601Note that a pragma is not a statement, so in contexts where a statement 2602sequence is required, you can't just write a pragma on its own. You have 2603to add a ``null`` statement. 2604 2605.. code-block:: ada 2606 2607 if ... then 2608 ... -- some statements 2609 else 2610 pragma Assert (Num_Cases < 10); 2611 null; 2612 end if; 2613 2614.. _Conditionalizing_Declarations: 2615 2616Conditionalizing Declarations 2617^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2618 2619In some cases it may be necessary to conditionalize declarations to meet 2620different requirements. For example we might want a bit string whose length 2621is set to meet some hardware message requirement. 2622 2623This may be possible using declare blocks controlled 2624by conditional constants: 2625 2626.. code-block:: ada 2627 2628 if Small_Machine then 2629 declare 2630 X : Bit_String (1 .. 10); 2631 begin 2632 ... 2633 end; 2634 else 2635 declare 2636 X : Large_Bit_String (1 .. 1000); 2637 begin 2638 ... 2639 end; 2640 end if; 2641 2642Note that in this approach, both declarations are analyzed by the 2643compiler so this can only be used where both declarations are legal, 2644even though one of them will not be used. 2645 2646Another approach is to define integer constants, e.g., ``Bits_Per_Word``, 2647or Boolean constants, e.g., ``Little_Endian``, and then write declarations 2648that are parameterized by these constants. For example 2649 2650.. code-block:: ada 2651 2652 for Rec use 2653 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word; 2654 end record; 2655 2656If ``Bits_Per_Word`` is set to 32, this generates either 2657 2658.. code-block:: ada 2659 2660 for Rec use 2661 Field1 at 0 range 0 .. 32; 2662 end record; 2663 2664for the big endian case, or 2665 2666.. code-block:: ada 2667 2668 for Rec use record 2669 Field1 at 0 range 10 .. 32; 2670 end record; 2671 2672for the little endian case. Since a powerful subset of Ada expression 2673notation is usable for creating static constants, clever use of this 2674feature can often solve quite difficult problems in conditionalizing 2675compilation (note incidentally that in Ada 95, the little endian 2676constant was introduced as ``System.Default_Bit_Order``, so you do not 2677need to define this one yourself). 2678 2679.. _Use_of_Alternative_Implementations: 2680 2681Use of Alternative Implementations 2682^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2683 2684In some cases, none of the approaches described above are adequate. This 2685can occur for example if the set of declarations required is radically 2686different for two different configurations. 2687 2688In this situation, the official Ada way of dealing with conditionalizing 2689such code is to write separate units for the different cases. As long as 2690this does not result in excessive duplication of code, this can be done 2691without creating maintenance problems. The approach is to share common 2692code as far as possible, and then isolate the code and declarations 2693that are different. Subunits are often a convenient method for breaking 2694out a piece of a unit that is to be conditionalized, with separate files 2695for different versions of the subunit for different targets, where the 2696build script selects the right one to give to the compiler. 2697 2698.. index:: Subunits (and conditional compilation) 2699 2700As an example, consider a situation where a new feature in Ada 2005 2701allows something to be done in a really nice way. But your code must be able 2702to compile with an Ada 95 compiler. Conceptually you want to say: 2703 2704.. code-block:: ada 2705 2706 if Ada_2005 then 2707 ... neat Ada 2005 code 2708 else 2709 ... not quite as neat Ada 95 code 2710 end if; 2711 2712where ``Ada_2005`` is a Boolean constant. 2713 2714But this won't work when ``Ada_2005`` is set to ``False``, 2715since the ``then`` clause will be illegal for an Ada 95 compiler. 2716(Recall that although such unreachable code would eventually be deleted 2717by the compiler, it still needs to be legal. If it uses features 2718introduced in Ada 2005, it will be illegal in Ada 95.) 2719 2720So instead we write 2721 2722.. code-block:: ada 2723 2724 procedure Insert is separate; 2725 2726Then we have two files for the subunit ``Insert``, with the two sets of 2727code. 2728If the package containing this is called ``File_Queries``, then we might 2729have two files 2730 2731* :file:`file_queries-insert-2005.adb` 2732* :file:`file_queries-insert-95.adb` 2733 2734and the build script renames the appropriate file to :file:`file_queries-insert.adb` and then carries out the compilation. 2735 2736This can also be done with project files' naming schemes. For example: 2737 2738.. code-block:: gpr 2739 2740 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada"; 2741 2742Note also that with project files it is desirable to use a different extension 2743than :file:`ads` / :file:`adb` for alternative versions. Otherwise a naming 2744conflict may arise through another commonly used feature: to declare as part 2745of the project a set of directories containing all the sources obeying the 2746default naming scheme. 2747 2748The use of alternative units is certainly feasible in all situations, 2749and for example the Ada part of the GNAT run-time is conditionalized 2750based on the target architecture using this approach. As a specific example, 2751consider the implementation of the AST feature in VMS. There is one 2752spec: :file:`s-asthan.ads` which is the same for all architectures, and three 2753bodies: 2754 2755* :file:`s-asthan.adb` 2756 used for all non-VMS operating systems 2757 2758* :file:`s-asthan-vms-alpha.adb` 2759 used for VMS on the Alpha 2760 2761* :file:`s-asthan-vms-ia64.adb` 2762 used for VMS on the ia64 2763 2764The dummy version :file:`s-asthan.adb` simply raises exceptions noting that 2765this operating system feature is not available, and the two remaining 2766versions interface with the corresponding versions of VMS to provide 2767VMS-compatible AST handling. The GNAT build script knows the architecture 2768and operating system, and automatically selects the right version, 2769renaming it if necessary to :file:`s-asthan.adb` before the run-time build. 2770 2771Another style for arranging alternative implementations is through Ada's 2772access-to-subprogram facility. 2773In case some functionality is to be conditionally included, 2774you can declare an access-to-procedure variable ``Ref`` that is initialized 2775to designate a 'do nothing' procedure, and then invoke ``Ref.all`` 2776when appropriate. 2777In some library package, set ``Ref`` to ``Proc'Access`` for some 2778procedure ``Proc`` that performs the relevant processing. 2779The initialization only occurs if the library package is included in the 2780program. 2781The same idea can also be implemented using tagged types and dispatching 2782calls. 2783 2784.. _Preprocessing: 2785 2786Preprocessing 2787^^^^^^^^^^^^^ 2788 2789.. index:: Preprocessing 2790 2791Although it is quite possible to conditionalize code without the use of 2792C-style preprocessing, as described earlier in this section, it is 2793nevertheless convenient in some cases to use the C approach. Moreover, 2794older Ada compilers have often provided some preprocessing capability, 2795so legacy code may depend on this approach, even though it is not 2796standard. 2797 2798To accommodate such use, GNAT provides a preprocessor (modeled to a large 2799extent on the various preprocessors that have been used 2800with legacy code on other compilers, to enable easier transition). 2801 2802.. index:: gnatprep 2803 2804The preprocessor may be used in two separate modes. It can be used quite 2805separately from the compiler, to generate a separate output source file 2806that is then fed to the compiler as a separate step. This is the 2807``gnatprep`` utility, whose use is fully described in 2808:ref:`Preprocessing_with_gnatprep`. 2809 2810The preprocessing language allows such constructs as 2811 2812.. code-block:: c 2813 2814 #if DEBUG or else (PRIORITY > 4) then 2815 sequence of declarations 2816 #else 2817 completely different sequence of declarations 2818 #end if; 2819 2820The values of the symbols ``DEBUG`` and ``PRIORITY`` can be 2821defined either on the command line or in a separate file. 2822 2823The other way of running the preprocessor is even closer to the C style and 2824often more convenient. In this approach the preprocessing is integrated into 2825the compilation process. The compiler is given the preprocessor input which 2826includes ``#if`` lines etc, and then the compiler carries out the 2827preprocessing internally and processes the resulting output. 2828For more details on this approach, see :ref:`Integrated_Preprocessing`. 2829 2830.. _Preprocessing_with_gnatprep: 2831 2832Preprocessing with ``gnatprep`` 2833------------------------------- 2834 2835.. index:: ! gnatprep 2836.. index:: Preprocessing (gnatprep) 2837 2838This section discusses how to use GNAT's ``gnatprep`` utility for simple 2839preprocessing. 2840Although designed for use with GNAT, ``gnatprep`` does not depend on any 2841special GNAT features. 2842For further discussion of conditional compilation in general, see 2843:ref:`Conditional_Compilation`. 2844 2845.. _Preprocessing_Symbols: 2846 2847Preprocessing Symbols 2848^^^^^^^^^^^^^^^^^^^^^ 2849 2850Preprocessing symbols are defined in *definition files* and referenced in the 2851sources to be preprocessed. A preprocessing symbol is an identifier, following 2852normal Ada (case-insensitive) rules for its syntax, with the restriction that 2853all characters need to be in the ASCII set (no accented letters). 2854 2855.. _Using_gnatprep: 2856 2857Using ``gnatprep`` 2858^^^^^^^^^^^^^^^^^^ 2859 2860To call ``gnatprep`` use: 2861 2862.. code-block:: sh 2863 2864 $ gnatprep [ switches ] infile outfile [ deffile ] 2865 2866where 2867 2868* *switches* 2869 is an optional sequence of switches as described in the next section. 2870 2871* *infile* 2872 is the full name of the input file, which is an Ada source 2873 file containing preprocessor directives. 2874 2875* *outfile* 2876 is the full name of the output file, which is an Ada source 2877 in standard Ada form. When used with GNAT, this file name will 2878 normally have an ``ads`` or ``adb`` suffix. 2879 2880* ``deffile`` 2881 is the full name of a text file containing definitions of 2882 preprocessing symbols to be referenced by the preprocessor. This argument is 2883 optional, and can be replaced by the use of the :switch:`-D` switch. 2884 2885 2886.. _Switches_for_gnatprep: 2887 2888Switches for ``gnatprep`` 2889^^^^^^^^^^^^^^^^^^^^^^^^^ 2890 2891.. index:: --version (gnatprep) 2892 2893:switch:`--version` 2894 Display Copyright and version, then exit disregarding all other options. 2895 2896.. index:: --help (gnatprep) 2897 2898:switch:`--help` 2899 If :switch:`--version` was not used, display usage and then exit disregarding 2900 all other options. 2901 2902.. index:: -b (gnatprep) 2903 2904:switch:`-b` 2905 Causes both preprocessor lines and the lines deleted by 2906 preprocessing to be replaced by blank lines in the output source file, 2907 preserving line numbers in the output file. 2908 2909.. index:: -c (gnatprep) 2910 2911:switch:`-c` 2912 Causes both preprocessor lines and the lines deleted 2913 by preprocessing to be retained in the output source as comments marked 2914 with the special string ``"--! "``. This option will result in line numbers 2915 being preserved in the output file. 2916 2917.. index:: -C (gnatprep) 2918 2919:switch:`-C` 2920 Causes comments to be scanned. Normally comments are ignored by gnatprep. 2921 If this option is specified, then comments are scanned and any $symbol 2922 substitutions performed as in program text. This is particularly useful 2923 when structured comments are used (e.g., for programs written in a 2924 pre-2014 version of the SPARK Ada subset). Note that this switch is not 2925 available when doing integrated preprocessing (it would be useless in 2926 this context since comments are ignored by the compiler in any case). 2927 2928.. index:: -D (gnatprep) 2929 2930:switch:`-D{symbol}[={value}]` 2931 Defines a new preprocessing symbol with the specified value. If no value is given 2932 on the command line, then symbol is considered to be ``True``. This switch 2933 can be used in place of a definition file. 2934 2935.. index:: -r (gnatprep) 2936 2937:switch:`-r` 2938 Causes a ``Source_Reference`` pragma to be generated that 2939 references the original input file, so that error messages will use 2940 the file name of this original file. The use of this switch implies 2941 that preprocessor lines are not to be removed from the file, so its 2942 use will force ``-b`` mode if ``-c`` 2943 has not been specified explicitly. 2944 2945 Note that if the file to be preprocessed contains multiple units, then 2946 it will be necessary to ``gnatchop`` the output file from 2947 ``gnatprep``. If a ``Source_Reference`` pragma is present 2948 in the preprocessed file, it will be respected by 2949 ``gnatchop -r`` 2950 so that the final chopped files will correctly refer to the original 2951 input source file for ``gnatprep``. 2952 2953.. index:: -s (gnatprep) 2954 2955:switch:`-s` 2956 Causes a sorted list of symbol names and values to be 2957 listed on the standard output file. 2958 2959.. index:: -T (gnatprep) 2960 2961:switch:`-T` 2962 Use LF as line terminators when writing files. By default the line terminator 2963 of the host (LF under unix, CR/LF under Windows) is used. 2964 2965.. index:: -u (gnatprep) 2966 2967:switch:`-u` 2968 Causes undefined symbols to be treated as having the value FALSE in the context 2969 of a preprocessor test. In the absence of this option, an undefined symbol in 2970 a ``#if`` or ``#elsif`` test will be treated as an error. 2971 2972.. index:: -v (gnatprep) 2973 2974:switch:`-v` 2975 Verbose mode: generates more output about work done. 2976 2977 2978Note: if neither :switch:`-b` nor :switch:`-c` is present, 2979then preprocessor lines and 2980deleted lines are completely removed from the output, unless -r is 2981specified, in which case -b is assumed. 2982 2983 2984.. _Form_of_Definitions_File: 2985 2986Form of Definitions File 2987^^^^^^^^^^^^^^^^^^^^^^^^ 2988 2989The definitions file contains lines of the form:: 2990 2991 symbol := value 2992 2993where ``symbol`` is a preprocessing symbol, and ``value`` is one of the following: 2994 2995* Empty, corresponding to a null substitution, 2996* A string literal using normal Ada syntax, or 2997* Any sequence of characters from the set {letters, digits, period, underline}. 2998 2999Comment lines may also appear in the definitions file, starting with 3000the usual ``--``, 3001and comments may be added to the definitions lines. 3002 3003 3004.. _Form_of_Input_Text_for_gnatprep: 3005 3006Form of Input Text for ``gnatprep`` 3007^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3008 3009The input text may contain preprocessor conditional inclusion lines, 3010as well as general symbol substitution sequences. 3011 3012The preprocessor conditional inclusion commands have the form: 3013 3014.. code-block:: c 3015 3016 #if <expression> [then] 3017 lines 3018 #elsif <expression> [then] 3019 lines 3020 #elsif <expression> [then] 3021 lines 3022 ... 3023 #else 3024 lines 3025 #end if; 3026 3027In this example, <expression> is defined by the following grammar:: 3028 3029 <expression> ::= <symbol> 3030 <expression> ::= <symbol> = "<value>" 3031 <expression> ::= <symbol> = <symbol> 3032 <expression> ::= <symbol> = <integer> 3033 <expression> ::= <symbol> > <integer> 3034 <expression> ::= <symbol> >= <integer> 3035 <expression> ::= <symbol> < <integer> 3036 <expression> ::= <symbol> <= <integer> 3037 <expression> ::= <symbol> 'Defined 3038 <expression> ::= not <expression> 3039 <expression> ::= <expression> and <expression> 3040 <expression> ::= <expression> or <expression> 3041 <expression> ::= <expression> and then <expression> 3042 <expression> ::= <expression> or else <expression> 3043 <expression> ::= ( <expression> ) 3044 3045Note the following restriction: it is not allowed to have "and" or "or" 3046following "not" in the same expression without parentheses. For example, this 3047is not allowed: 3048 3049.. code-block:: ada 3050 3051 not X or Y 3052 3053This can be expressed instead as one of the following forms: 3054 3055.. code-block:: ada 3056 3057 (not X) or Y 3058 not (X or Y) 3059 3060For the first test (<expression> ::= <symbol>) the symbol must have 3061either the value true or false, that is to say the right-hand of the 3062symbol definition must be one of the (case-insensitive) literals 3063``True`` or ``False``. If the value is true, then the 3064corresponding lines are included, and if the value is false, they are 3065excluded. 3066 3067When comparing a symbol to an integer, the integer is any non negative 3068literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or 30692#11#. The symbol value must also be a non negative integer. Integer values 3070in the range 0 .. 2**31-1 are supported. 3071 3072The test (<expression> ::= <symbol>'Defined) is true only if 3073the symbol has been defined in the definition file or by a :switch:`-D` 3074switch on the command line. Otherwise, the test is false. 3075 3076The equality tests are case insensitive, as are all the preprocessor lines. 3077 3078If the symbol referenced is not defined in the symbol definitions file, 3079then the effect depends on whether or not switch :switch:`-u` 3080is specified. If so, then the symbol is treated as if it had the value 3081false and the test fails. If this switch is not specified, then 3082it is an error to reference an undefined symbol. It is also an error to 3083reference a symbol that is defined with a value other than ``True`` 3084or ``False``. 3085 3086The use of the ``not`` operator inverts the sense of this logical test. 3087The ``not`` operator cannot be combined with the ``or`` or ``and`` 3088operators, without parentheses. For example, "if not X or Y then" is not 3089allowed, but "if (not X) or Y then" and "if not (X or Y) then" are. 3090 3091The ``then`` keyword is optional as shown 3092 3093The ``#`` must be the first non-blank character on a line, but 3094otherwise the format is free form. Spaces or tabs may appear between 3095the ``#`` and the keyword. The keywords and the symbols are case 3096insensitive as in normal Ada code. Comments may be used on a 3097preprocessor line, but other than that, no other tokens may appear on a 3098preprocessor line. Any number of ``elsif`` clauses can be present, 3099including none at all. The ``else`` is optional, as in Ada. 3100 3101The ``#`` marking the start of a preprocessor line must be the first 3102non-blank character on the line, i.e., it must be preceded only by 3103spaces or horizontal tabs. 3104 3105Symbol substitution outside of preprocessor lines is obtained by using 3106the sequence:: 3107 3108 $symbol 3109 3110anywhere within a source line, except in a comment or within a 3111string literal. The identifier 3112following the ``$`` must match one of the symbols defined in the symbol 3113definition file, and the result is to substitute the value of the 3114symbol in place of ``$symbol`` in the output file. 3115 3116Note that although the substitution of strings within a string literal 3117is not possible, it is possible to have a symbol whose defined value is 3118a string literal. So instead of setting XYZ to ``hello`` and writing: 3119 3120.. code-block:: ada 3121 3122 Header : String := "$XYZ"; 3123 3124you should set XYZ to ``"hello"`` and write: 3125 3126.. code-block:: ada 3127 3128 Header : String := $XYZ; 3129 3130and then the substitution will occur as desired. 3131 3132 3133.. _Integrated_Preprocessing: 3134 3135Integrated Preprocessing 3136------------------------ 3137 3138As noted above, a file to be preprocessed consists of Ada source code 3139in which preprocessing lines have been inserted. However, 3140instead of using ``gnatprep`` to explicitly preprocess a file as a separate 3141step before compilation, you can carry out the preprocessing implicitly 3142as part of compilation. Such *integrated preprocessing*, which is the common 3143style with C, is performed when either or both of the following switches 3144are passed to the compiler: 3145 3146 * :switch:`-gnatep`, which specifies the *preprocessor data file*. 3147 This file dictates how the source files will be preprocessed (e.g., which 3148 symbol definition files apply to which sources). 3149 3150 * :switch:`-gnateD`, which defines values for preprocessing symbols. 3151 3152Integrated preprocessing applies only to Ada source files, it is 3153not available for configuration pragma files. 3154 3155With integrated preprocessing, the output from the preprocessor is not, 3156by default, written to any external file. Instead it is passed 3157internally to the compiler. To preserve the result of 3158preprocessing in a file, either run ``gnatprep`` 3159in standalone mode or else supply the :switch:`-gnateG` switch 3160(described below) to the compiler. 3161 3162When using project files: 3163 3164 * the builder switch :switch:`-x` should be used if any Ada source is 3165 compiled with :switch:`gnatep=`, so that the compiler finds the 3166 *preprocessor data file*. 3167 3168 * the preprocessing data file and the symbol definition files should be 3169 located in the source directories of the project. 3170 3171Note that the ``gnatmake`` switch :switch:`-m` will almost 3172always trigger recompilation for sources that are preprocessed, 3173because ``gnatmake`` cannot compute the checksum of the source after 3174preprocessing. 3175 3176The actual preprocessing function is described in detail in 3177:ref:`Preprocessing_with_gnatprep`. This section explains the switches 3178that relate to integrated preprocessing. 3179 3180.. index:: -gnatep (gcc) 3181 3182:switch:`-gnatep={preprocessor_data_file}` 3183 This switch specifies the file name (without directory 3184 information) of the preprocessor data file. Either place this file 3185 in one of the source directories, or, when using project 3186 files, reference the project file's directory via the 3187 ``project_name'Project_Dir`` project attribute; e.g: 3188 3189 .. code-block:: gpr 3190 3191 project Prj is 3192 package Compiler is 3193 for Switches ("Ada") use 3194 ("-gnatep=" & Prj'Project_Dir & "prep.def"); 3195 end Compiler; 3196 end Prj; 3197 3198 A preprocessor data file is a text file that contains *preprocessor 3199 control lines*. A preprocessor control line directs the preprocessing of 3200 either a particular source file, or, analogous to ``others`` in Ada, 3201 all sources not specified elsewhere in the preprocessor data file. 3202 A preprocessor control line 3203 can optionally identify a *definition file* that assigns values to 3204 preprocessor symbols, as well as a list of switches that relate to 3205 preprocessing. 3206 Empty lines and comments (using Ada syntax) are also permitted, with no 3207 semantic effect. 3208 3209 Here's an example of a preprocessor data file: 3210 3211 .. code-block:: ada 3212 3213 "toto.adb" "prep.def" -u 3214 -- Preprocess toto.adb, using definition file prep.def 3215 -- Undefined symbols are treated as False 3216 3217 * -c -DVERSION=V101 3218 -- Preprocess all other sources without using a definition file 3219 -- Suppressed lined are commented 3220 -- Symbol VERSION has the value V101 3221 3222 "tata.adb" "prep2.def" -s 3223 -- Preprocess tata.adb, using definition file prep2.def 3224 -- List all symbols with their values 3225 3226 A preprocessor control line has the following syntax: 3227 3228 :: 3229 3230 <preprocessor_control_line> ::= 3231 <preprocessor_input> [ <definition_file_name> ] { <switch> } 3232 3233 <preprocessor_input> ::= <source_file_name> | '*' 3234 3235 <definition_file_name> ::= <string_literal> 3236 3237 <source_file_name> := <string_literal> 3238 3239 <switch> := (See below for list) 3240 3241 Thus each preprocessor control line starts with either a literal string or 3242 the character '*': 3243 3244 * A literal string is the file name (without directory information) of the source 3245 file that will be input to the preprocessor. 3246 3247 * The character '*' is a wild-card indicator; the additional parameters on the line 3248 indicate the preprocessing for all the sources 3249 that are not specified explicitly on other lines (the order of the lines is not 3250 significant). 3251 3252 It is an error to have two lines with the same file name or two 3253 lines starting with the character '*'. 3254 3255 After the file name or '*', an optional literal string specifies the name of 3256 the definition file to be used for preprocessing 3257 (:ref:`Form_of_Definitions_File`). The definition files are found by the 3258 compiler in one of the source directories. In some cases, when compiling 3259 a source in a directory other than the current directory, if the definition 3260 file is in the current directory, it may be necessary to add the current 3261 directory as a source directory through the :switch:`-I` switch; otherwise 3262 the compiler would not find the definition file. 3263 3264 Finally, switches similar to those of ``gnatprep`` may optionally appear: 3265 3266 :switch:`-b` 3267 Causes both preprocessor lines and the lines deleted by 3268 preprocessing to be replaced by blank lines, preserving the line number. 3269 This switch is always implied; however, if specified after :switch:`-c` 3270 it cancels the effect of :switch:`-c`. 3271 3272 3273 :switch:`-c` 3274 Causes both preprocessor lines and the lines deleted 3275 by preprocessing to be retained as comments marked 3276 with the special string '`--!`'. 3277 3278 3279 :switch:`-D{symbol}={new_value}` 3280 Define or redefine ``symbol`` to have ``new_value`` as its value. 3281 The permitted form for ``symbol`` is either an Ada identifier, or any Ada reserved word 3282 aside from ``if``, 3283 ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``. 3284 The permitted form for ``new_value`` is a literal string, an Ada identifier or any Ada reserved 3285 word. A symbol declared with this switch replaces a symbol with the 3286 same name defined in a definition file. 3287 3288 3289 :switch:`-s` 3290 Causes a sorted list of symbol names and values to be 3291 listed on the standard output file. 3292 3293 3294 :switch:`-u` 3295 Causes undefined symbols to be treated as having the value ``FALSE`` 3296 in the context 3297 of a preprocessor test. In the absence of this option, an undefined symbol in 3298 a ``#if`` or ``#elsif`` test will be treated as an error. 3299 3300 3301.. index:: -gnateD (gcc) 3302 3303:switch:`-gnateD{symbol}[={new_value}]` 3304 Define or redefine ``symbol`` to have ``new_value`` as its value. If no value 3305 is supplied, then the value of ``symbol`` is ``True``. 3306 The form of ``symbol`` is an identifier, following normal Ada (case-insensitive) 3307 rules for its syntax, and ``new_value`` is either an arbitrary string between double 3308 quotes or any sequence (including an empty sequence) of characters from the 3309 set (letters, digits, period, underline). 3310 Ada reserved words may be used as symbols, with the exceptions of ``if``, 3311 ``else``, ``elsif``, ``end``, ``and``, ``or`` and ``then``. 3312 3313 Examples: 3314 3315 :: 3316 3317 -gnateDToto=Tata 3318 -gnateDFoo 3319 -gnateDFoo=\"Foo-Bar\" 3320 3321 A symbol declared with this switch on the command line replaces a 3322 symbol with the same name either in a definition file or specified with a 3323 switch :switch:`-D` in the preprocessor data file. 3324 3325 This switch is similar to switch :switch:`-D` of ``gnatprep``. 3326 3327 3328:switch:`-gnateG` 3329 When integrated preprocessing is performed on source file :file:`filename.extension`, 3330 create or overwrite :file:`filename.extension.prep` to contain 3331 the result of the preprocessing. 3332 For example if the source file is :file:`foo.adb` then 3333 the output file will be :file:`foo.adb.prep`. 3334 3335 3336.. _Mixed_Language_Programming: 3337 3338Mixed Language Programming 3339========================== 3340 3341.. index:: Mixed Language Programming 3342 3343This section describes how to develop a mixed-language program, 3344with a focus on combining Ada with C or C++. 3345 3346.. _Interfacing_to_C: 3347 3348Interfacing to C 3349---------------- 3350 3351Interfacing Ada with a foreign language such as C involves using 3352compiler directives to import and/or export entity definitions in each 3353language -- using ``extern`` statements in C, for instance, and the 3354``Import``, ``Export``, and ``Convention`` pragmas in Ada. 3355A full treatment of these topics is provided in Appendix B, section 1 3356of the Ada Reference Manual. 3357 3358There are two ways to build a program using GNAT that contains some Ada 3359sources and some foreign language sources, depending on whether or not 3360the main subprogram is written in Ada. Here is a source example with 3361the main subprogram in Ada: 3362 3363.. code-block:: c 3364 3365 /* file1.c */ 3366 #include <stdio.h> 3367 3368 void print_num (int num) 3369 { 3370 printf ("num is %d.\\n", num); 3371 return; 3372 } 3373 3374.. code-block:: c 3375 3376 /* file2.c */ 3377 3378 /* num_from_Ada is declared in my_main.adb */ 3379 extern int num_from_Ada; 3380 3381 int get_num (void) 3382 { 3383 return num_from_Ada; 3384 } 3385 3386.. code-block:: ada 3387 3388 -- my_main.adb 3389 procedure My_Main is 3390 3391 -- Declare then export an Integer entity called num_from_Ada 3392 My_Num : Integer := 10; 3393 pragma Export (C, My_Num, "num_from_Ada"); 3394 3395 -- Declare an Ada function spec for Get_Num, then use 3396 -- C function get_num for the implementation. 3397 function Get_Num return Integer; 3398 pragma Import (C, Get_Num, "get_num"); 3399 3400 -- Declare an Ada procedure spec for Print_Num, then use 3401 -- C function print_num for the implementation. 3402 procedure Print_Num (Num : Integer); 3403 pragma Import (C, Print_Num, "print_num"); 3404 3405 begin 3406 Print_Num (Get_Num); 3407 end My_Main; 3408 3409To build this example: 3410 3411* First compile the foreign language files to 3412 generate object files: 3413 3414 .. code-block:: sh 3415 3416 $ gcc -c file1.c 3417 $ gcc -c file2.c 3418 3419* Then, compile the Ada units to produce a set of object files and ALI 3420 files: 3421 3422 .. code-block:: sh 3423 3424 $ gnatmake -c my_main.adb 3425 3426* Run the Ada binder on the Ada main program: 3427 3428 .. code-block:: sh 3429 3430 $ gnatbind my_main.ali 3431 3432* Link the Ada main program, the Ada objects and the other language 3433 objects: 3434 3435 .. code-block:: sh 3436 3437 $ gnatlink my_main.ali file1.o file2.o 3438 3439The last three steps can be grouped in a single command: 3440 3441.. code-block:: sh 3442 3443 $ gnatmake my_main.adb -largs file1.o file2.o 3444 3445 3446.. index:: Binder output file 3447 3448If the main program is in a language other than Ada, then you may have 3449more than one entry point into the Ada subsystem. You must use a special 3450binder option to generate callable routines that initialize and 3451finalize the Ada units (:ref:`Binding_with_Non-Ada_Main_Programs`). 3452Calls to the initialization and finalization routines must be inserted 3453in the main program, or some other appropriate point in the code. The 3454call to initialize the Ada units must occur before the first Ada 3455subprogram is called, and the call to finalize the Ada units must occur 3456after the last Ada subprogram returns. The binder will place the 3457initialization and finalization subprograms into the 3458:file:`b~xxx.adb` file where they can be accessed by your C 3459sources. To illustrate, we have the following example: 3460 3461.. code-block:: c 3462 3463 /* main.c */ 3464 extern void adainit (void); 3465 extern void adafinal (void); 3466 extern int add (int, int); 3467 extern int sub (int, int); 3468 3469 int main (int argc, char *argv[]) 3470 { 3471 int a = 21, b = 7; 3472 3473 adainit(); 3474 3475 /* Should print "21 + 7 = 28" */ 3476 printf ("%d + %d = %d\\n", a, b, add (a, b)); 3477 3478 /* Should print "21 - 7 = 14" */ 3479 printf ("%d - %d = %d\\n", a, b, sub (a, b)); 3480 3481 adafinal(); 3482 } 3483 3484.. code-block:: ada 3485 3486 -- unit1.ads 3487 package Unit1 is 3488 function Add (A, B : Integer) return Integer; 3489 pragma Export (C, Add, "add"); 3490 end Unit1; 3491 3492.. code-block:: ada 3493 3494 -- unit1.adb 3495 package body Unit1 is 3496 function Add (A, B : Integer) return Integer is 3497 begin 3498 return A + B; 3499 end Add; 3500 end Unit1; 3501 3502.. code-block:: ada 3503 3504 -- unit2.ads 3505 package Unit2 is 3506 function Sub (A, B : Integer) return Integer; 3507 pragma Export (C, Sub, "sub"); 3508 end Unit2; 3509 3510.. code-block:: ada 3511 3512 -- unit2.adb 3513 package body Unit2 is 3514 function Sub (A, B : Integer) return Integer is 3515 begin 3516 return A - B; 3517 end Sub; 3518 end Unit2; 3519 3520The build procedure for this application is similar to the last 3521example's: 3522 3523* First, compile the foreign language files to generate object files: 3524 3525 .. code-block:: sh 3526 3527 $ gcc -c main.c 3528 3529 3530* Next, compile the Ada units to produce a set of object files and ALI 3531 files: 3532 3533 .. code-block:: sh 3534 3535 $ gnatmake -c unit1.adb 3536 $ gnatmake -c unit2.adb 3537 3538* Run the Ada binder on every generated ALI file. Make sure to use the 3539 :switch:`-n` option to specify a foreign main program: 3540 3541 .. code-block:: sh 3542 3543 $ gnatbind -n unit1.ali unit2.ali 3544 3545* Link the Ada main program, the Ada objects and the foreign language 3546 objects. You need only list the last ALI file here: 3547 3548 .. code-block:: sh 3549 3550 $ gnatlink unit2.ali main.o -o exec_file 3551 3552 This procedure yields a binary executable called :file:`exec_file`. 3553 3554Depending on the circumstances (for example when your non-Ada main object 3555does not provide symbol ``main``), you may also need to instruct the 3556GNAT linker not to include the standard startup objects by passing the 3557:switch:`-nostartfiles` switch to ``gnatlink``. 3558 3559.. _Calling_Conventions: 3560 3561Calling Conventions 3562------------------- 3563 3564.. index:: Foreign Languages 3565 3566.. index:: Calling Conventions 3567 3568GNAT follows standard calling sequence conventions and will thus interface 3569to any other language that also follows these conventions. The following 3570Convention identifiers are recognized by GNAT: 3571 3572 3573.. index:: Interfacing to Ada 3574 3575.. index:: Other Ada compilers 3576 3577.. index:: Convention Ada 3578 3579``Ada`` 3580 This indicates that the standard Ada calling sequence will be 3581 used and all Ada data items may be passed without any limitations in the 3582 case where GNAT is used to generate both the caller and callee. It is also 3583 possible to mix GNAT generated code and code generated by another Ada 3584 compiler. In this case, the data types should be restricted to simple 3585 cases, including primitive types. Whether complex data types can be passed 3586 depends on the situation. Probably it is safe to pass simple arrays, such 3587 as arrays of integers or floats. Records may or may not work, depending 3588 on whether both compilers lay them out identically. Complex structures 3589 involving variant records, access parameters, tasks, or protected types, 3590 are unlikely to be able to be passed. 3591 3592 Note that in the case of GNAT running 3593 on a platform that supports HP Ada 83, a higher degree of compatibility 3594 can be guaranteed, and in particular records are laid out in an identical 3595 manner in the two compilers. Note also that if output from two different 3596 compilers is mixed, the program is responsible for dealing with elaboration 3597 issues. Probably the safest approach is to write the main program in the 3598 version of Ada other than GNAT, so that it takes care of its own elaboration 3599 requirements, and then call the GNAT-generated adainit procedure to ensure 3600 elaboration of the GNAT components. Consult the documentation of the other 3601 Ada compiler for further details on elaboration. 3602 3603 However, it is not possible to mix the tasking run time of GNAT and 3604 HP Ada 83, All the tasking operations must either be entirely within 3605 GNAT compiled sections of the program, or entirely within HP Ada 83 3606 compiled sections of the program. 3607 3608.. index:: Interfacing to Assembly 3609 3610.. index:: Convention Assembler 3611 3612 3613``Assembler`` 3614 Specifies assembler as the convention. In practice this has the 3615 same effect as convention Ada (but is not equivalent in the sense of being 3616 considered the same convention). 3617 3618.. index:: Convention Asm 3619 3620.. index:: Asm 3621 3622``Asm`` 3623 Equivalent to Assembler. 3624 3625 .. index:: Interfacing to COBOL 3626 3627 .. index:: Convention COBOL 3628 3629.. index:: COBOL 3630 3631``COBOL`` 3632 Data will be passed according to the conventions described 3633 in section B.4 of the Ada Reference Manual. 3634 3635.. index:: C 3636.. index:: Interfacing to C 3637 3638.. index:: Convention C 3639 3640 3641``C`` 3642 Data will be passed according to the conventions described 3643 in section B.3 of the Ada Reference Manual. 3644 3645 A note on interfacing to a C 'varargs' function: 3646 3647 .. index:: C varargs function 3648 .. index:: Interfacing to C varargs function 3649 .. index:: varargs function interfaces 3650 3651 In C, ``varargs`` allows a function to take a variable number of 3652 arguments. There is no direct equivalent in this to Ada. One 3653 approach that can be used is to create a C wrapper for each 3654 different profile and then interface to this C wrapper. For 3655 example, to print an ``int`` value using ``printf``, 3656 create a C function ``printfi`` that takes two arguments, a 3657 pointer to a string and an int, and calls ``printf``. 3658 Then in the Ada program, use pragma ``Import`` to 3659 interface to ``printfi``. 3660 3661 It may work on some platforms to directly interface to 3662 a ``varargs`` function by providing a specific Ada profile 3663 for a particular call. However, this does not work on 3664 all platforms, since there is no guarantee that the 3665 calling sequence for a two argument normal C function 3666 is the same as for calling a ``varargs`` C function with 3667 the same two arguments. 3668 3669.. index:: Convention Default 3670 3671.. index:: Default 3672 3673``Default`` 3674 Equivalent to C. 3675 3676.. index:: Convention External 3677 3678.. index:: External 3679 3680``External`` 3681 Equivalent to C. 3682 3683.. index:: C++ 3684.. index:: Interfacing to C++ 3685 3686.. index:: Convention C++ 3687 3688 3689``C_Plus_Plus`` (or ``CPP``) 3690 This stands for C++. For most purposes this is identical to C. 3691 See the separate description of the specialized GNAT pragmas relating to 3692 C++ interfacing for further details. 3693 3694.. index:: Fortran 3695.. index:: Interfacing to Fortran 3696.. index:: Convention Fortran 3697 3698 3699``Fortran`` 3700 Data will be passed according to the conventions described 3701 in section B.5 of the Ada Reference Manual. 3702 3703 3704``Intrinsic`` 3705 This applies to an intrinsic operation, as defined in the Ada 3706 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram, 3707 this means that the body of the subprogram is provided by the compiler itself, 3708 usually by means of an efficient code sequence, and that the user does not 3709 supply an explicit body for it. In an application program, the pragma may 3710 be applied to the following sets of names: 3711 3712 3713 * Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic. 3714 The corresponding subprogram declaration must have 3715 two formal parameters. The 3716 first one must be a signed integer type or a modular type with a binary 3717 modulus, and the second parameter must be of type Natural. 3718 The return type must be the same as the type of the first argument. The size 3719 of this type can only be 8, 16, 32, or 64. 3720 3721 3722 * Binary arithmetic operators: '+', '-', '*', '/'. 3723 The corresponding operator declaration must have parameters and result type 3724 that have the same root numeric type (for example, all three are long_float 3725 types). This simplifies the definition of operations that use type checking 3726 to perform dimensional checks: 3727 3728 3729 .. code-block:: ada 3730 3731 type Distance is new Long_Float; 3732 type Time is new Long_Float; 3733 type Velocity is new Long_Float; 3734 function "/" (D : Distance; T : Time) 3735 return Velocity; 3736 pragma Import (Intrinsic, "/"); 3737 3738 This common idiom is often programmed with a generic definition and an 3739 explicit body. The pragma makes it simpler to introduce such declarations. 3740 It incurs no overhead in compilation time or code size, because it is 3741 implemented as a single machine instruction. 3742 3743 3744 * General subprogram entities. This is used to bind an Ada subprogram 3745 declaration to 3746 a compiler builtin by name with back-ends where such interfaces are 3747 available. A typical example is the set of ``__builtin`` functions 3748 exposed by the GCC back-end, as in the following example: 3749 3750 3751 .. code-block:: ada 3752 3753 function builtin_sqrt (F : Float) return Float; 3754 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf"); 3755 3756 Most of the GCC builtins are accessible this way, and as for other 3757 import conventions (e.g. C), it is the user's responsibility to ensure 3758 that the Ada subprogram profile matches the underlying builtin 3759 expectations. 3760 3761.. index:: Stdcall 3762.. index:: Convention Stdcall 3763 3764``Stdcall`` 3765 This is relevant only to Windows implementations of GNAT, 3766 and specifies that the ``Stdcall`` calling sequence will be used, 3767 as defined by the NT API. Nevertheless, to ease building 3768 cross-platform bindings this convention will be handled as a ``C`` calling 3769 convention on non-Windows platforms. 3770 3771.. index:: DLL 3772.. index:: Convention DLL 3773 3774 3775``DLL`` 3776 This is equivalent to ``Stdcall``. 3777 3778.. index:: Win32 3779.. index:: Convention Win32 3780 3781 3782``Win32`` 3783 This is equivalent to ``Stdcall``. 3784 3785.. index:: Stubbed 3786.. index:: Convention Stubbed 3787 3788 3789``Stubbed`` 3790 This is a special convention that indicates that the compiler 3791 should provide a stub body that raises ``Program_Error``. 3792 3793GNAT additionally provides a useful pragma ``Convention_Identifier`` 3794that can be used to parameterize conventions and allow additional synonyms 3795to be specified. For example if you have legacy code in which the convention 3796identifier Fortran77 was used for Fortran, you can use the configuration 3797pragma: 3798 3799.. code-block:: ada 3800 3801 pragma Convention_Identifier (Fortran77, Fortran); 3802 3803And from now on the identifier Fortran77 may be used as a convention 3804identifier (for example in an ``Import`` pragma) with the same 3805meaning as Fortran. 3806 3807 3808.. _Building_Mixed_Ada_and_C++_Programs: 3809 3810Building Mixed Ada and C++ Programs 3811----------------------------------- 3812 3813A programmer inexperienced with mixed-language development may find that 3814building an application containing both Ada and C++ code can be a 3815challenge. This section gives a few hints that should make this task easier. 3816 3817.. _Interfacing_to_C++: 3818 3819Interfacing to C++ 3820^^^^^^^^^^^^^^^^^^ 3821 3822GNAT supports interfacing with the G++ compiler (or any C++ compiler 3823generating code that is compatible with the G++ Application Binary 3824Interface ---see http://www.codesourcery.com/archives/cxx-abi). 3825 3826Interfacing can be done at 3 levels: simple data, subprograms, and 3827classes. In the first two cases, GNAT offers a specific ``Convention C_Plus_Plus`` 3828(or ``CPP``) that behaves exactly like ``Convention C``. 3829Usually, C++ mangles the names of subprograms. To generate proper mangled 3830names automatically, see :ref:`Generating_Ada_Bindings_for_C_and_C++_headers`). 3831This problem can also be addressed manually in two ways: 3832 3833* by modifying the C++ code in order to force a C convention using 3834 the ``extern "C"`` syntax. 3835 3836* by figuring out the mangled name (using e.g. ``nm``) and using it as the 3837 Link_Name argument of the pragma import. 3838 3839Interfacing at the class level can be achieved by using the GNAT specific 3840pragmas such as ``CPP_Constructor``. See the :title:`GNAT_Reference_Manual` for additional information. 3841 3842.. _Linking_a_Mixed_C++_and_Ada_Program: 3843 3844Linking a Mixed C++ & Ada Program 3845^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3846 3847Usually the linker of the C++ development system must be used to link 3848mixed applications because most C++ systems will resolve elaboration 3849issues (such as calling constructors on global class instances) 3850transparently during the link phase. GNAT has been adapted to ease the 3851use of a foreign linker for the last phase. Three cases can be 3852considered: 3853 3854 3855* Using GNAT and G++ (GNU C++ compiler) from the same GCC installation: 3856 The C++ linker can simply be called by using the C++ specific driver 3857 called ``g++``. 3858 3859 Note that if the C++ code uses inline functions, you will need to 3860 compile your C++ code with the :switch:`-fkeep-inline-functions` switch in 3861 order to provide an existing function implementation that the Ada code can 3862 link with. 3863 3864 .. code-block:: sh 3865 3866 $ g++ -c -fkeep-inline-functions file1.C 3867 $ g++ -c -fkeep-inline-functions file2.C 3868 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++ 3869 3870 3871* Using GNAT and G++ from two different GCC installations: If both 3872 compilers are on the :envvar`PATH`, the previous method may be used. It is 3873 important to note that environment variables such as 3874 :envvar:`C_INCLUDE_PATH`, :envvar:`GCC_EXEC_PREFIX`, 3875 :envvar:`BINUTILS_ROOT`, and 3876 :envvar:`GCC_ROOT` will affect both compilers 3877 at the same time and may make one of the two compilers operate 3878 improperly if set during invocation of the wrong compiler. It is also 3879 very important that the linker uses the proper :file:`libgcc.a` GCC 3880 library -- that is, the one from the C++ compiler installation. The 3881 implicit link command as suggested in the ``gnatmake`` command 3882 from the former example can be replaced by an explicit link command with 3883 the full-verbosity option in order to verify which library is used: 3884 3885 .. code-block:: sh 3886 3887 $ gnatbind ada_unit 3888 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++ 3889 3890 If there is a problem due to interfering environment variables, it can 3891 be worked around by using an intermediate script. The following example 3892 shows the proper script to use when GNAT has not been installed at its 3893 default location and g++ has been installed at its default location: 3894 3895 .. code-block:: sh 3896 3897 $ cat ./my_script 3898 #!/bin/sh 3899 unset BINUTILS_ROOT 3900 unset GCC_ROOT 3901 c++ $* 3902 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script 3903 3904 3905* Using a non-GNU C++ compiler: The commands previously described can be 3906 used to insure that the C++ linker is used. Nonetheless, you need to add 3907 a few more parameters to the link command line, depending on the exception 3908 mechanism used. 3909 3910 If the ``setjmp`` / ``longjmp`` exception mechanism is used, only the paths 3911 to the ``libgcc`` libraries are required: 3912 3913 .. code-block:: sh 3914 3915 $ cat ./my_script 3916 #!/bin/sh 3917 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a 3918 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script 3919 3920 3921 where CC is the name of the non-GNU C++ compiler. 3922 3923 If the "zero cost" exception mechanism is used, and the platform 3924 supports automatic registration of exception tables (e.g., Solaris), 3925 paths to more objects are required: 3926 3927 .. code-block:: sh 3928 3929 $ cat ./my_script 3930 #!/bin/sh 3931 CC gcc -print-file-name=crtbegin.o $* \\ 3932 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\ 3933 gcc -print-file-name=crtend.o 3934 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script 3935 3936 3937 If the "zero cost exception" mechanism is used, and the platform 3938 doesn't support automatic registration of exception tables (e.g., HP-UX 3939 or AIX), the simple approach described above will not work and 3940 a pre-linking phase using GNAT will be necessary. 3941 3942 3943Another alternative is to use the :command:`gprbuild` multi-language builder 3944which has a large knowledge base and knows how to link Ada and C++ code 3945together automatically in most cases. 3946 3947.. _A_Simple_Example: 3948 3949A Simple Example 3950^^^^^^^^^^^^^^^^ 3951 3952The following example, provided as part of the GNAT examples, shows how 3953to achieve procedural interfacing between Ada and C++ in both 3954directions. The C++ class A has two methods. The first method is exported 3955to Ada by the means of an extern C wrapper function. The second method 3956calls an Ada subprogram. On the Ada side, The C++ calls are modelled by 3957a limited record with a layout comparable to the C++ class. The Ada 3958subprogram, in turn, calls the C++ method. So, starting from the C++ 3959main program, the process passes back and forth between the two 3960languages. 3961 3962Here are the compilation commands: 3963 3964.. code-block:: sh 3965 3966 $ gnatmake -c simple_cpp_interface 3967 $ g++ -c cpp_main.C 3968 $ g++ -c ex7.C 3969 $ gnatbind -n simple_cpp_interface 3970 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o 3971 3972Here are the corresponding sources: 3973 3974.. code-block:: cpp 3975 3976 //cpp_main.C 3977 3978 #include "ex7.h" 3979 3980 extern "C" { 3981 void adainit (void); 3982 void adafinal (void); 3983 void method1 (A *t); 3984 } 3985 3986 void method1 (A *t) 3987 { 3988 t->method1 (); 3989 } 3990 3991 int main () 3992 { 3993 A obj; 3994 adainit (); 3995 obj.method2 (3030); 3996 adafinal (); 3997 } 3998 3999.. code-block:: cpp 4000 4001 //ex7.h 4002 4003 class Origin { 4004 public: 4005 int o_value; 4006 }; 4007 class A : public Origin { 4008 public: 4009 void method1 (void); 4010 void method2 (int v); 4011 A(); 4012 int a_value; 4013 }; 4014 4015.. code-block:: cpp 4016 4017 //ex7.C 4018 4019 #include "ex7.h" 4020 #include <stdio.h> 4021 4022 extern "C" { void ada_method2 (A *t, int v);} 4023 4024 void A::method1 (void) 4025 { 4026 a_value = 2020; 4027 printf ("in A::method1, a_value = %d \\n",a_value); 4028 } 4029 4030 void A::method2 (int v) 4031 { 4032 ada_method2 (this, v); 4033 printf ("in A::method2, a_value = %d \\n",a_value); 4034 } 4035 4036 A::A(void) 4037 { 4038 a_value = 1010; 4039 printf ("in A::A, a_value = %d \\n",a_value); 4040 } 4041 4042.. code-block:: ada 4043 4044 -- simple_cpp_interface.ads 4045 with System; 4046 package Simple_Cpp_Interface is 4047 type A is limited 4048 record 4049 Vptr : System.Address; 4050 O_Value : Integer; 4051 A_Value : Integer; 4052 end record; 4053 pragma Convention (C, A); 4054 4055 procedure Method1 (This : in out A); 4056 pragma Import (C, Method1); 4057 4058 procedure Ada_Method2 (This : in out A; V : Integer); 4059 pragma Export (C, Ada_Method2); 4060 4061 end Simple_Cpp_Interface; 4062 4063.. code-block:: ada 4064 4065 -- simple_cpp_interface.adb 4066 package body Simple_Cpp_Interface is 4067 4068 procedure Ada_Method2 (This : in out A; V : Integer) is 4069 begin 4070 Method1 (This); 4071 This.A_Value := V; 4072 end Ada_Method2; 4073 4074 end Simple_Cpp_Interface; 4075 4076 4077.. _Interfacing_with_C++_constructors: 4078 4079Interfacing with C++ constructors 4080^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4081 4082In order to interface with C++ constructors GNAT provides the 4083``pragma CPP_Constructor`` (see the :title:`GNAT_Reference_Manual` 4084for additional information). 4085In this section we present some common uses of C++ constructors 4086in mixed-languages programs in GNAT. 4087 4088Let us assume that we need to interface with the following 4089C++ class: 4090 4091.. code-block:: cpp 4092 4093 class Root { 4094 public: 4095 int a_value; 4096 int b_value; 4097 virtual int Get_Value (); 4098 Root(); // Default constructor 4099 Root(int v); // 1st non-default constructor 4100 Root(int v, int w); // 2nd non-default constructor 4101 }; 4102 4103For this purpose we can write the following package spec (further 4104information on how to build this spec is available in 4105:ref:`Interfacing_with_C++_at_the_Class_Level` and 4106:ref:`Generating_Ada_Bindings_for_C_and_C++_headers`). 4107 4108.. code-block:: ada 4109 4110 with Interfaces.C; use Interfaces.C; 4111 package Pkg_Root is 4112 type Root is tagged limited record 4113 A_Value : int; 4114 B_Value : int; 4115 end record; 4116 pragma Import (CPP, Root); 4117 4118 function Get_Value (Obj : Root) return int; 4119 pragma Import (CPP, Get_Value); 4120 4121 function Constructor return Root; 4122 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev"); 4123 4124 function Constructor (v : Integer) return Root; 4125 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei"); 4126 4127 function Constructor (v, w : Integer) return Root; 4128 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii"); 4129 end Pkg_Root; 4130 4131On the Ada side the constructor is represented by a function (whose 4132name is arbitrary) that returns the classwide type corresponding to 4133the imported C++ class. Although the constructor is described as a 4134function, it is typically a procedure with an extra implicit argument 4135(the object being initialized) at the implementation level. GNAT 4136issues the appropriate call, whatever it is, to get the object 4137properly initialized. 4138 4139Constructors can only appear in the following contexts: 4140 4141* On the right side of an initialization of an object of type ``T``. 4142* On the right side of an initialization of a record component of type ``T``. 4143* In an Ada 2005 limited aggregate. 4144* In an Ada 2005 nested limited aggregate. 4145* In an Ada 2005 limited aggregate that initializes an object built in 4146 place by an extended return statement. 4147 4148In a declaration of an object whose type is a class imported from C++, 4149either the default C++ constructor is implicitly called by GNAT, or 4150else the required C++ constructor must be explicitly called in the 4151expression that initializes the object. For example: 4152 4153.. code-block:: ada 4154 4155 Obj1 : Root; 4156 Obj2 : Root := Constructor; 4157 Obj3 : Root := Constructor (v => 10); 4158 Obj4 : Root := Constructor (30, 40); 4159 4160The first two declarations are equivalent: in both cases the default C++ 4161constructor is invoked (in the former case the call to the constructor is 4162implicit, and in the latter case the call is explicit in the object 4163declaration). ``Obj3`` is initialized by the C++ non-default constructor 4164that takes an integer argument, and ``Obj4`` is initialized by the 4165non-default C++ constructor that takes two integers. 4166 4167Let us derive the imported C++ class in the Ada side. For example: 4168 4169.. code-block:: ada 4170 4171 type DT is new Root with record 4172 C_Value : Natural := 2009; 4173 end record; 4174 4175In this case the components DT inherited from the C++ side must be 4176initialized by a C++ constructor, and the additional Ada components 4177of type DT are initialized by GNAT. The initialization of such an 4178object is done either by default, or by means of a function returning 4179an aggregate of type DT, or by means of an extension aggregate. 4180 4181.. code-block:: ada 4182 4183 Obj5 : DT; 4184 Obj6 : DT := Function_Returning_DT (50); 4185 Obj7 : DT := (Constructor (30,40) with C_Value => 50); 4186 4187The declaration of ``Obj5`` invokes the default constructors: the 4188C++ default constructor of the parent type takes care of the initialization 4189of the components inherited from Root, and GNAT takes care of the default 4190initialization of the additional Ada components of type DT (that is, 4191``C_Value`` is initialized to value 2009). The order of invocation of 4192the constructors is consistent with the order of elaboration required by 4193Ada and C++. That is, the constructor of the parent type is always called 4194before the constructor of the derived type. 4195 4196Let us now consider a record that has components whose type is imported 4197from C++. For example: 4198 4199.. code-block:: ada 4200 4201 type Rec1 is limited record 4202 Data1 : Root := Constructor (10); 4203 Value : Natural := 1000; 4204 end record; 4205 4206 type Rec2 (D : Integer := 20) is limited record 4207 Rec : Rec1; 4208 Data2 : Root := Constructor (D, 30); 4209 end record; 4210 4211The initialization of an object of type ``Rec2`` will call the 4212non-default C++ constructors specified for the imported components. 4213For example: 4214 4215.. code-block:: ada 4216 4217 Obj8 : Rec2 (40); 4218 4219Using Ada 2005 we can use limited aggregates to initialize an object 4220invoking C++ constructors that differ from those specified in the type 4221declarations. For example: 4222 4223.. code-block:: ada 4224 4225 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16), 4226 others => <>), 4227 others => <>); 4228 4229The above declaration uses an Ada 2005 limited aggregate to 4230initialize ``Obj9``, and the C++ constructor that has two integer 4231arguments is invoked to initialize the ``Data1`` component instead 4232of the constructor specified in the declaration of type ``Rec1``. In 4233Ada 2005 the box in the aggregate indicates that unspecified components 4234are initialized using the expression (if any) available in the component 4235declaration. That is, in this case discriminant ``D`` is initialized 4236to value ``20``, ``Value`` is initialized to value 1000, and the 4237non-default C++ constructor that handles two integers takes care of 4238initializing component ``Data2`` with values ``20,30``. 4239 4240In Ada 2005 we can use the extended return statement to build the Ada 4241equivalent to C++ non-default constructors. For example: 4242 4243.. code-block:: ada 4244 4245 function Constructor (V : Integer) return Rec2 is 4246 begin 4247 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20), 4248 others => <>), 4249 others => <>) do 4250 -- Further actions required for construction of 4251 -- objects of type Rec2 4252 ... 4253 end record; 4254 end Constructor; 4255 4256In this example the extended return statement construct is used to 4257build in place the returned object whose components are initialized 4258by means of a limited aggregate. Any further action associated with 4259the constructor can be placed inside the construct. 4260 4261.. _Interfacing_with_C++_at_the_Class_Level: 4262 4263Interfacing with C++ at the Class Level 4264^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4265 4266In this section we demonstrate the GNAT features for interfacing with 4267C++ by means of an example making use of Ada 2005 abstract interface 4268types. This example consists of a classification of animals; classes 4269have been used to model our main classification of animals, and 4270interfaces provide support for the management of secondary 4271classifications. We first demonstrate a case in which the types and 4272constructors are defined on the C++ side and imported from the Ada 4273side, and latter the reverse case. 4274 4275The root of our derivation will be the ``Animal`` class, with a 4276single private attribute (the ``Age`` of the animal), a constructor, 4277and two public primitives to set and get the value of this attribute. 4278 4279.. code-block:: cpp 4280 4281 class Animal { 4282 public: 4283 virtual void Set_Age (int New_Age); 4284 virtual int Age (); 4285 Animal() {Age_Count = 0;}; 4286 private: 4287 int Age_Count; 4288 }; 4289 4290Abstract interface types are defined in C++ by means of classes with pure 4291virtual functions and no data members. In our example we will use two 4292interfaces that provide support for the common management of ``Carnivore`` 4293and ``Domestic`` animals: 4294 4295.. code-block:: cpp 4296 4297 class Carnivore { 4298 public: 4299 virtual int Number_Of_Teeth () = 0; 4300 }; 4301 4302 class Domestic { 4303 public: 4304 virtual void Set_Owner (char* Name) = 0; 4305 }; 4306 4307Using these declarations, we can now say that a ``Dog`` is an animal that is 4308both Carnivore and Domestic, that is: 4309 4310.. code-block:: cpp 4311 4312 class Dog : Animal, Carnivore, Domestic { 4313 public: 4314 virtual int Number_Of_Teeth (); 4315 virtual void Set_Owner (char* Name); 4316 4317 Dog(); // Constructor 4318 private: 4319 int Tooth_Count; 4320 char *Owner; 4321 }; 4322 4323In the following examples we will assume that the previous declarations are 4324located in a file named :file:`animals.h`. The following package demonstrates 4325how to import these C++ declarations from the Ada side: 4326 4327.. code-block:: ada 4328 4329 with Interfaces.C.Strings; use Interfaces.C.Strings; 4330 package Animals is 4331 type Carnivore is limited interface; 4332 pragma Convention (C_Plus_Plus, Carnivore); 4333 function Number_Of_Teeth (X : Carnivore) 4334 return Natural is abstract; 4335 4336 type Domestic is limited interface; 4337 pragma Convention (C_Plus_Plus, Domestic); 4338 procedure Set_Owner 4339 (X : in out Domestic; 4340 Name : Chars_Ptr) is abstract; 4341 4342 type Animal is tagged limited record 4343 Age : Natural; 4344 end record; 4345 pragma Import (C_Plus_Plus, Animal); 4346 4347 procedure Set_Age (X : in out Animal; Age : Integer); 4348 pragma Import (C_Plus_Plus, Set_Age); 4349 4350 function Age (X : Animal) return Integer; 4351 pragma Import (C_Plus_Plus, Age); 4352 4353 function New_Animal return Animal; 4354 pragma CPP_Constructor (New_Animal); 4355 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev"); 4356 4357 type Dog is new Animal and Carnivore and Domestic with record 4358 Tooth_Count : Natural; 4359 Owner : Chars_Ptr; 4360 end record; 4361 pragma Import (C_Plus_Plus, Dog); 4362 4363 function Number_Of_Teeth (A : Dog) return Natural; 4364 pragma Import (C_Plus_Plus, Number_Of_Teeth); 4365 4366 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr); 4367 pragma Import (C_Plus_Plus, Set_Owner); 4368 4369 function New_Dog return Dog; 4370 pragma CPP_Constructor (New_Dog); 4371 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev"); 4372 end Animals; 4373 4374Thanks to the compatibility between GNAT run-time structures and the C++ ABI, 4375interfacing with these C++ classes is easy. The only requirement is that all 4376the primitives and components must be declared exactly in the same order in 4377the two languages. 4378 4379Regarding the abstract interfaces, we must indicate to the GNAT compiler by 4380means of a ``pragma Convention (C_Plus_Plus)``, the convention used to pass 4381the arguments to the called primitives will be the same as for C++. For the 4382imported classes we use ``pragma Import`` with convention ``C_Plus_Plus`` 4383to indicate that they have been defined on the C++ side; this is required 4384because the dispatch table associated with these tagged types will be built 4385in the C++ side and therefore will not contain the predefined Ada primitives 4386which Ada would otherwise expect. 4387 4388As the reader can see there is no need to indicate the C++ mangled names 4389associated with each subprogram because it is assumed that all the calls to 4390these primitives will be dispatching calls. The only exception is the 4391constructor, which must be registered with the compiler by means of 4392``pragma CPP_Constructor`` and needs to provide its associated C++ 4393mangled name because the Ada compiler generates direct calls to it. 4394 4395With the above packages we can now declare objects of type Dog on the Ada side 4396and dispatch calls to the corresponding subprograms on the C++ side. We can 4397also extend the tagged type Dog with further fields and primitives, and 4398override some of its C++ primitives on the Ada side. For example, here we have 4399a type derivation defined on the Ada side that inherits all the dispatching 4400primitives of the ancestor from the C++ side. 4401 4402.. code-block:: ada 4403 4404 with Animals; use Animals; 4405 package Vaccinated_Animals is 4406 type Vaccinated_Dog is new Dog with null record; 4407 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean; 4408 end Vaccinated_Animals; 4409 4410It is important to note that, because of the ABI compatibility, the programmer 4411does not need to add any further information to indicate either the object 4412layout or the dispatch table entry associated with each dispatching operation. 4413 4414Now let us define all the types and constructors on the Ada side and export 4415them to C++, using the same hierarchy of our previous example: 4416 4417.. code-block:: ada 4418 4419 with Interfaces.C.Strings; 4420 use Interfaces.C.Strings; 4421 package Animals is 4422 type Carnivore is limited interface; 4423 pragma Convention (C_Plus_Plus, Carnivore); 4424 function Number_Of_Teeth (X : Carnivore) 4425 return Natural is abstract; 4426 4427 type Domestic is limited interface; 4428 pragma Convention (C_Plus_Plus, Domestic); 4429 procedure Set_Owner 4430 (X : in out Domestic; 4431 Name : Chars_Ptr) is abstract; 4432 4433 type Animal is tagged record 4434 Age : Natural; 4435 end record; 4436 pragma Convention (C_Plus_Plus, Animal); 4437 4438 procedure Set_Age (X : in out Animal; Age : Integer); 4439 pragma Export (C_Plus_Plus, Set_Age); 4440 4441 function Age (X : Animal) return Integer; 4442 pragma Export (C_Plus_Plus, Age); 4443 4444 function New_Animal return Animal'Class; 4445 pragma Export (C_Plus_Plus, New_Animal); 4446 4447 type Dog is new Animal and Carnivore and Domestic with record 4448 Tooth_Count : Natural; 4449 Owner : String (1 .. 30); 4450 end record; 4451 pragma Convention (C_Plus_Plus, Dog); 4452 4453 function Number_Of_Teeth (A : Dog) return Natural; 4454 pragma Export (C_Plus_Plus, Number_Of_Teeth); 4455 4456 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr); 4457 pragma Export (C_Plus_Plus, Set_Owner); 4458 4459 function New_Dog return Dog'Class; 4460 pragma Export (C_Plus_Plus, New_Dog); 4461 end Animals; 4462 4463Compared with our previous example the only differences are the use of 4464``pragma Convention`` (instead of ``pragma Import``), and the use of 4465``pragma Export`` to indicate to the GNAT compiler that the primitives will 4466be available to C++. Thanks to the ABI compatibility, on the C++ side there is 4467nothing else to be done; as explained above, the only requirement is that all 4468the primitives and components are declared in exactly the same order. 4469 4470For completeness, let us see a brief C++ main program that uses the 4471declarations available in :file:`animals.h` (presented in our first example) to 4472import and use the declarations from the Ada side, properly initializing and 4473finalizing the Ada run-time system along the way: 4474 4475.. code-block:: cpp 4476 4477 #include "animals.h" 4478 #include <iostream> 4479 using namespace std; 4480 4481 void Check_Carnivore (Carnivore *obj) {...} 4482 void Check_Domestic (Domestic *obj) {...} 4483 void Check_Animal (Animal *obj) {...} 4484 void Check_Dog (Dog *obj) {...} 4485 4486 extern "C" { 4487 void adainit (void); 4488 void adafinal (void); 4489 Dog* new_dog (); 4490 } 4491 4492 void test () 4493 { 4494 Dog *obj = new_dog(); // Ada constructor 4495 Check_Carnivore (obj); // Check secondary DT 4496 Check_Domestic (obj); // Check secondary DT 4497 Check_Animal (obj); // Check primary DT 4498 Check_Dog (obj); // Check primary DT 4499 } 4500 4501 int main () 4502 { 4503 adainit (); test(); adafinal (); 4504 return 0; 4505 } 4506 4507.. _Generating_Ada_Bindings_for_C_and_C++_headers: 4508 4509Generating Ada Bindings for C and C++ headers 4510--------------------------------------------- 4511 4512.. index:: Binding generation (for C and C++ headers) 4513.. index:: C headers (binding generation) 4514.. index:: C++ headers (binding generation) 4515 4516GNAT includes a binding generator for C and C++ headers which is 4517intended to do 95% of the tedious work of generating Ada specs from C 4518or C++ header files. 4519 4520Note that this capability is not intended to generate 100% correct Ada specs, 4521and will is some cases require manual adjustments, although it can often 4522be used out of the box in practice. 4523 4524Some of the known limitations include: 4525 4526* only very simple character constant macros are translated into Ada 4527 constants. Function macros (macros with arguments) are partially translated 4528 as comments, to be completed manually if needed. 4529* some extensions (e.g. vector types) are not supported 4530* pointers to pointers or complex structures are mapped to System.Address 4531* identifiers with identical name (except casing) will generate compilation 4532 errors (e.g. ``shm_get`` vs ``SHM_GET``). 4533 4534The code generated is using the Ada 2005 syntax, which makes it 4535easier to interface with other languages than previous versions of Ada. 4536 4537.. _Running_the_binding_generator: 4538 4539Running the Binding Generator 4540^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4541 4542The binding generator is part of the ``gcc`` compiler and can be 4543invoked via the :switch:`-fdump-ada-spec` switch, which will generate Ada 4544spec files for the header files specified on the command line, and all 4545header files needed by these files transitively. For example: 4546 4547.. code-block:: sh 4548 4549 $ g++ -c -fdump-ada-spec -C /usr/include/time.h 4550 $ gcc -c -gnat05 *.ads 4551 4552will generate, under GNU/Linux, the following files: :file:`time_h.ads`, 4553:file:`bits_time_h.ads`, :file:`stddef_h.ads`, :file:`bits_types_h.ads` which 4554correspond to the files :file:`/usr/include/time.h`, 4555:file:`/usr/include/bits/time.h`, etc..., and will then compile these Ada specs 4556in Ada 2005 mode. 4557 4558The :switch:`-C` switch tells ``gcc`` to extract comments from headers, 4559and will attempt to generate corresponding Ada comments. 4560 4561If you want to generate a single Ada file and not the transitive closure, you 4562can use instead the :switch:`-fdump-ada-spec-slim` switch. 4563 4564You can optionally specify a parent unit, of which all generated units will 4565be children, using :switch:`-fada-spec-parent={unit}`. 4566 4567Note that we recommend when possible to use the *g++* driver to 4568generate bindings, even for most C headers, since this will in general 4569generate better Ada specs. For generating bindings for C++ headers, it is 4570mandatory to use the *g++* command, or *gcc -x c++* which 4571is equivalent in this case. If *g++* cannot work on your C headers 4572because of incompatibilities between C and C++, then you can fallback to 4573``gcc`` instead. 4574 4575For an example of better bindings generated from the C++ front-end, 4576the name of the parameters (when available) are actually ignored by the C 4577front-end. Consider the following C header: 4578 4579.. code-block:: c 4580 4581 extern void foo (int variable); 4582 4583with the C front-end, ``variable`` is ignored, and the above is handled as: 4584 4585.. code-block:: c 4586 4587 extern void foo (int); 4588 4589generating a generic: 4590 4591.. code-block:: ada 4592 4593 procedure foo (param1 : int); 4594 4595with the C++ front-end, the name is available, and we generate: 4596 4597.. code-block:: ada 4598 4599 procedure foo (variable : int); 4600 4601In some cases, the generated bindings will be more complete or more meaningful 4602when defining some macros, which you can do via the :switch:`-D` switch. This 4603is for example the case with :file:`Xlib.h` under GNU/Linux: 4604 4605.. code-block:: sh 4606 4607 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h 4608 4609The above will generate more complete bindings than a straight call without 4610the :switch:`-DXLIB_ILLEGAL_ACCESS` switch. 4611 4612In other cases, it is not possible to parse a header file in a stand-alone 4613manner, because other include files need to be included first. In this 4614case, the solution is to create a small header file including the needed 4615``#include`` and possible ``#define`` directives. For example, to 4616generate Ada bindings for :file:`readline/readline.h`, you need to first 4617include :file:`stdio.h`, so you can create a file with the following two 4618lines in e.g. :file:`readline1.h`: 4619 4620.. code-block:: cpp 4621 4622 #include <stdio.h> 4623 #include <readline/readline.h> 4624 4625and then generate Ada bindings from this file: 4626 4627.. code-block:: sh 4628 4629 $ g++ -c -fdump-ada-spec readline1.h 4630 4631 4632.. _Generating_bindings_for_C++_headers: 4633 4634Generating Bindings for C++ Headers 4635^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4636 4637Generating bindings for C++ headers is done using the same options, always 4638with the *g++* compiler. Note that generating Ada spec from C++ headers is a 4639much more complex job and support for C++ headers is much more limited that 4640support for C headers. As a result, you will need to modify the resulting 4641bindings by hand more extensively when using C++ headers. 4642 4643In this mode, C++ classes will be mapped to Ada tagged types, constructors 4644will be mapped using the ``CPP_Constructor`` pragma, and when possible, 4645multiple inheritance of abstract classes will be mapped to Ada interfaces 4646(see the *Interfacing to C++* section in the :title:`GNAT Reference Manual` 4647for additional information on interfacing to C++). 4648 4649For example, given the following C++ header file: 4650 4651.. code-block:: cpp 4652 4653 class Carnivore { 4654 public: 4655 virtual int Number_Of_Teeth () = 0; 4656 }; 4657 4658 class Domestic { 4659 public: 4660 virtual void Set_Owner (char* Name) = 0; 4661 }; 4662 4663 class Animal { 4664 public: 4665 int Age_Count; 4666 virtual void Set_Age (int New_Age); 4667 }; 4668 4669 class Dog : Animal, Carnivore, Domestic { 4670 public: 4671 int Tooth_Count; 4672 char *Owner; 4673 4674 virtual int Number_Of_Teeth (); 4675 virtual void Set_Owner (char* Name); 4676 4677 Dog(); 4678 }; 4679 4680The corresponding Ada code is generated: 4681 4682.. code-block:: ada 4683 4684 package Class_Carnivore is 4685 type Carnivore is limited interface; 4686 pragma Import (CPP, Carnivore); 4687 4688 function Number_Of_Teeth (this : access Carnivore) return int is abstract; 4689 end; 4690 use Class_Carnivore; 4691 4692 package Class_Domestic is 4693 type Domestic is limited interface; 4694 pragma Import (CPP, Domestic); 4695 4696 procedure Set_Owner 4697 (this : access Domestic; 4698 Name : Interfaces.C.Strings.chars_ptr) is abstract; 4699 end; 4700 use Class_Domestic; 4701 4702 package Class_Animal is 4703 type Animal is tagged limited record 4704 Age_Count : aliased int; 4705 end record; 4706 pragma Import (CPP, Animal); 4707 4708 procedure Set_Age (this : access Animal; New_Age : int); 4709 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi"); 4710 end; 4711 use Class_Animal; 4712 4713 package Class_Dog is 4714 type Dog is new Animal and Carnivore and Domestic with record 4715 Tooth_Count : aliased int; 4716 Owner : Interfaces.C.Strings.chars_ptr; 4717 end record; 4718 pragma Import (CPP, Dog); 4719 4720 function Number_Of_Teeth (this : access Dog) return int; 4721 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv"); 4722 4723 procedure Set_Owner 4724 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr); 4725 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc"); 4726 4727 function New_Dog return Dog; 4728 pragma CPP_Constructor (New_Dog); 4729 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev"); 4730 end; 4731 use Class_Dog; 4732 4733 4734.. _Switches_for_Ada_Binding_Generation: 4735 4736Switches 4737^^^^^^^^ 4738 4739.. index:: -fdump-ada-spec (gcc) 4740 4741:switch:`-fdump-ada-spec` 4742 Generate Ada spec files for the given header files transitively (including 4743 all header files that these headers depend upon). 4744 4745.. index:: -fdump-ada-spec-slim (gcc) 4746 4747:switch:`-fdump-ada-spec-slim` 4748 Generate Ada spec files for the header files specified on the command line 4749 only. 4750 4751.. index:: -fada-spec-parent (gcc) 4752 4753:switch:`-fada-spec-parent={unit}` 4754 Specifies that all files generated by :switch:`-fdump-ada-spec` are 4755 to be child units of the specified parent unit. 4756 4757.. index:: -C (gcc) 4758 4759:switch:`-C` 4760 Extract comments from headers and generate Ada comments in the Ada spec files. 4761 4762.. _Generating_C_Headers_for_Ada_Specifications: 4763 4764Generating C Headers for Ada Specifications 4765------------------------------------------- 4766 4767.. index:: Binding generation (for Ada specs) 4768.. index:: C headers (binding generation) 4769 4770GNAT includes a C header generator for Ada specifications which supports 4771Ada types that have a direct mapping to C types. This includes in particular 4772support for: 4773 4774* Scalar types 4775* Constrained arrays 4776* Records (untagged) 4777* Composition of the above types 4778* Constant declarations 4779* Object declarations 4780* Subprogram declarations 4781 4782Running the C Header Generator 4783^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 4784 4785The C header generator is part of the GNAT compiler and can be invoked via 4786the :switch:`-gnatceg` combination of switches, which will generate a :file:`.h` 4787file corresponding to the given input file (Ada spec or body). Note that 4788only spec files are processed in any case, so giving a spec or a body file 4789as input is equivalent. For example: 4790 4791.. code-block:: sh 4792 4793 $ gcc -c -gnatceg pack1.ads 4794 4795will generate a self-contained file called :file:`pack1.h` including 4796common definitions from the Ada Standard package, followed by the 4797definitions included in :file:`pack1.ads`, as well as all the other units 4798withed by this file. 4799 4800For instance, given the following Ada files: 4801 4802.. code-block:: ada 4803 4804 package Pack2 is 4805 type Int is range 1 .. 10; 4806 end Pack2; 4807 4808.. code-block:: ada 4809 4810 with Pack2; 4811 4812 package Pack1 is 4813 type Rec is record 4814 Field1, Field2 : Pack2.Int; 4815 end record; 4816 4817 Global : Rec := (1, 2); 4818 4819 procedure Proc1 (R : Rec); 4820 procedure Proc2 (R : in out Rec); 4821 end Pack1; 4822 4823The above ``gcc`` command will generate the following :file:`pack1.h` file: 4824 4825.. code-block:: c 4826 4827 /* Standard definitions skipped */ 4828 #ifndef PACK2_ADS 4829 #define PACK2_ADS 4830 typedef short_short_integer pack2__TintB; 4831 typedef pack2__TintB pack2__int; 4832 #endif /* PACK2_ADS */ 4833 4834 #ifndef PACK1_ADS 4835 #define PACK1_ADS 4836 typedef struct _pack1__rec { 4837 pack2__int field1; 4838 pack2__int field2; 4839 } pack1__rec; 4840 extern pack1__rec pack1__global; 4841 extern void pack1__proc1(const pack1__rec r); 4842 extern void pack1__proc2(pack1__rec *r); 4843 #endif /* PACK1_ADS */ 4844 4845You can then ``include`` :file:`pack1.h` from a C source file and use the types, 4846call subprograms, reference objects, and constants. 4847 4848.. _GNAT_and_Other_Compilation_Models: 4849 4850GNAT and Other Compilation Models 4851================================= 4852 4853This section compares the GNAT model with the approaches taken in 4854other environents, first the C/C++ model and then the mechanism that 4855has been used in other Ada systems, in particular those traditionally 4856used for Ada 83. 4857 4858.. _Comparison_between_GNAT_and_C/C++_Compilation_Models: 4859 4860Comparison between GNAT and C/C++ Compilation Models 4861---------------------------------------------------- 4862 4863The GNAT model of compilation is close to the C and C++ models. You can 4864think of Ada specs as corresponding to header files in C. As in C, you 4865don't need to compile specs; they are compiled when they are used. The 4866Ada |with| is similar in effect to the ``#include`` of a C 4867header. 4868 4869One notable difference is that, in Ada, you may compile specs separately 4870to check them for semantic and syntactic accuracy. This is not always 4871possible with C headers because they are fragments of programs that have 4872less specific syntactic or semantic rules. 4873 4874The other major difference is the requirement for running the binder, 4875which performs two important functions. First, it checks for 4876consistency. In C or C++, the only defense against assembling 4877inconsistent programs lies outside the compiler, in a makefile, for 4878example. The binder satisfies the Ada requirement that it be impossible 4879to construct an inconsistent program when the compiler is used in normal 4880mode. 4881 4882.. index:: Elaboration order control 4883 4884The other important function of the binder is to deal with elaboration 4885issues. There are also elaboration issues in C++ that are handled 4886automatically. This automatic handling has the advantage of being 4887simpler to use, but the C++ programmer has no control over elaboration. 4888Where ``gnatbind`` might complain there was no valid order of 4889elaboration, a C++ compiler would simply construct a program that 4890malfunctioned at run time. 4891 4892.. _Comparison_between_GNAT_and_Conventional_Ada_Library_Models: 4893 4894Comparison between GNAT and Conventional Ada Library Models 4895----------------------------------------------------------- 4896 4897This section is intended for Ada programmers who have 4898used an Ada compiler implementing the traditional Ada library 4899model, as described in the Ada Reference Manual. 4900 4901.. index:: GNAT library 4902 4903In GNAT, there is no 'library' in the normal sense. Instead, the set of 4904source files themselves acts as the library. Compiling Ada programs does 4905not generate any centralized information, but rather an object file and 4906a ALI file, which are of interest only to the binder and linker. 4907In a traditional system, the compiler reads information not only from 4908the source file being compiled, but also from the centralized library. 4909This means that the effect of a compilation depends on what has been 4910previously compiled. In particular: 4911 4912* When a unit is |withed|, the unit seen by the compiler corresponds 4913 to the version of the unit most recently compiled into the library. 4914 4915* Inlining is effective only if the necessary body has already been 4916 compiled into the library. 4917 4918* Compiling a unit may obsolete other units in the library. 4919 4920In GNAT, compiling one unit never affects the compilation of any other 4921units because the compiler reads only source files. Only changes to source 4922files can affect the results of a compilation. In particular: 4923 4924* When a unit is |withed|, the unit seen by the compiler corresponds 4925 to the source version of the unit that is currently accessible to the 4926 compiler. 4927 4928 .. index:: Inlining 4929 4930* Inlining requires the appropriate source files for the package or 4931 subprogram bodies to be available to the compiler. Inlining is always 4932 effective, independent of the order in which units are compiled. 4933 4934* Compiling a unit never affects any other compilations. The editing of 4935 sources may cause previous compilations to be out of date if they 4936 depended on the source file being modified. 4937 4938The most important result of these differences is that order of compilation 4939is never significant in GNAT. There is no situation in which one is 4940required to do one compilation before another. What shows up as order of 4941compilation requirements in the traditional Ada library becomes, in 4942GNAT, simple source dependencies; in other words, there is only a set 4943of rules saying what source files must be present when a file is 4944compiled. 4945 4946 4947.. _Using_GNAT_Files_with_External_Tools: 4948 4949Using GNAT Files with External Tools 4950==================================== 4951 4952This section explains how files that are produced by GNAT may be 4953used with tools designed for other languages. 4954 4955 4956.. _Using_Other_Utility_Programs_with_GNAT: 4957 4958Using Other Utility Programs with GNAT 4959-------------------------------------- 4960 4961The object files generated by GNAT are in standard system format and in 4962particular the debugging information uses this format. This means 4963programs generated by GNAT can be used with existing utilities that 4964depend on these formats. 4965 4966In general, any utility program that works with C will also often work with 4967Ada programs generated by GNAT. This includes software utilities such as 4968gprof (a profiling program), gdb (the FSF debugger), and utilities such 4969as Purify. 4970 4971 4972.. _The_External_Symbol_Naming_Scheme_of_GNAT: 4973 4974The External Symbol Naming Scheme of GNAT 4975----------------------------------------- 4976 4977In order to interpret the output from GNAT, when using tools that are 4978originally intended for use with other languages, it is useful to 4979understand the conventions used to generate link names from the Ada 4980entity names. 4981 4982All link names are in all lowercase letters. With the exception of library 4983procedure names, the mechanism used is simply to use the full expanded 4984Ada name with dots replaced by double underscores. For example, suppose 4985we have the following package spec: 4986 4987.. code-block:: ada 4988 4989 package QRS is 4990 MN : Integer; 4991 end QRS; 4992 4993.. index:: pragma Export 4994 4995The variable ``MN`` has a full expanded Ada name of ``QRS.MN``, so 4996the corresponding link name is ``qrs__mn``. 4997Of course if a ``pragma Export`` is used this may be overridden: 4998 4999.. code-block:: ada 5000 5001 package Exports is 5002 Var1 : Integer; 5003 pragma Export (Var1, C, External_Name => "var1_name"); 5004 Var2 : Integer; 5005 pragma Export (Var2, C, Link_Name => "var2_link_name"); 5006 end Exports; 5007 5008In this case, the link name for ``Var1`` is whatever link name the 5009C compiler would assign for the C function ``var1_name``. This typically 5010would be either ``var1_name`` or ``_var1_name``, depending on operating 5011system conventions, but other possibilities exist. The link name for 5012``Var2`` is ``var2_link_name``, and this is not operating system 5013dependent. 5014 5015One exception occurs for library level procedures. A potential ambiguity 5016arises between the required name ``_main`` for the C main program, 5017and the name we would otherwise assign to an Ada library level procedure 5018called ``Main`` (which might well not be the main program). 5019 5020To avoid this ambiguity, we attach the prefix ``_ada_`` to such 5021names. So if we have a library level procedure such as: 5022 5023.. code-block:: ada 5024 5025 procedure Hello (S : String); 5026 5027the external name of this procedure will be ``_ada_hello``. 5028