Debian Codegraph @

gcc/ada/doc/gnat_ugn/the_gnat_compilation_model.rst

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