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