[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3. Compiling Using gcc

This chapter discusses how to compile Ada programs using the gcc command. It also describes the set of switches that can be used to control the behavior of the compiler.

3.1 Compiling Programs  
3.2 Switches for gcc  
3.3 Search Paths and the Run-Time Library (RTL)  
3.4 Order of Compilation Issues  
3.5 Examples  


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.1 Compiling Programs

The first step in creating an executable program is to compile the units of the program using the gcc command. You must compile the following files:

You need not compile the following files

because they are compiled as part of compiling related units. GNAT package specs when the corresponding body is compiled, and subunits when the parent is compiled.

If you attempt to compile any of these files, you will get one of the following error messages (where fff is the name of the file you compiled):

 
cannot generate code for file fff (package spec)
to check package spec, use -gnatc

cannot generate code for file fff (missing subunits)
to check parent unit, use -gnatc

cannot generate code for file fff (subprogram spec)
to check subprogram spec, use -gnatc

cannot generate code for file fff (subunit)
to check subunit, use -gnatc

As indicated by the above error messages, if you want to submit one of these files to the compiler to check for correct semantics without generating code, then use the `-gnatc' switch.

The basic command for compiling a file containing an Ada unit is

 
$ gcc -c [switches] `file name'

where file name is the name of the Ada file (usually having an extension `.ads' for a spec or `.adb' for a body). You specify the `-c' switch to tell gcc to compile, but not link, the file. The result of a successful compilation is an object file, which has the same name as the source file but an extension of `.o' and an Ada Library Information (ALI) file, which also has the same name as the source file, but with `.ali' as the extension. GNAT creates these two output files in the current directory, but you may specify a source file in any directory using an absolute or relative path specification containing the directory information.

gcc is actually a driver program that looks at the extensions of the file arguments and loads the appropriate compiler. For example, the GNU C compiler is `cc1', and the Ada compiler is `gnat1'. These programs are in directories known to the driver program (in some configurations via environment variables you set), but need not be in your path. The gcc driver also calls the assembler and any other utilities needed to complete the generation of the required object files.

It is possible to supply several file names on the same gcc command. This causes gcc to call the appropriate compiler for each file. For example, the following command lists three separate files to be compiled:

 
$ gcc -c x.adb y.adb z.c

calls gnat1 (the Ada compiler) twice to compile `x.adb' and `y.adb', and cc1 (the C compiler) once to compile `z.c'. The compiler generates three object files `x.o', `y.o' and `z.o' and the two ALI files `x.ali' and `y.ali' from the Ada compilations. Any switches apply to all the files listed, except for `-gnatx' switches, which apply only to Ada compilations.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2 Switches for gcc

The gcc command accepts switches that control the compilation process. These switches are fully described in this section. First we briefly list all the switches, in alphabetical order, then we describe the switches in more detail in functionally grouped sections.

More switches exist for GCC than those documented here, especially for specific targets. However, their use is not recommended as they may change code generation in ways that are incompatible with the Ada run-time library, or can cause inconsistencies between compilation units.

3.2.1 Output and Error Message Control  
3.2.2 Warning Message Control  
3.2.3 Debugging and Assertion Control  
3.2.4 Validity Checking  
3.2.5 Style Checking  
3.2.6 Run-Time Checks  
3.2.7 Stack Overflow Checking  
3.2.8 Using gcc for Syntax Checking  
3.2.9 Using gcc for Semantic Checking  
3.2.10 Compiling Different Versions of Ada  
3.2.11 Character Set Control  
3.2.12 File Naming Control  
3.2.13 Subprogram Inlining Control  
3.2.14 Auxiliary Output Control  
3.2.15 Debugging Control  
3.2.16 Exception Handling Control  
3.2.17 Units to Sources Mapping Files  
3.2.18 Integrated Preprocessing  
3.2.19 Code Generation Control  

`-b target'
Compile your program to run on target, which is the name of a system configuration. You must have a GNAT cross-compiler built if target is not the same as your host system.

`-Bdir'
Load compiler executables (for example, gnat1, the Ada compiler) from dir instead of the default location. Only use this switch when multiple versions of the GNAT compiler are available. See the gcc manual page for further details. You would normally use the `-b' or `-V' switch instead.

`-c'
Compile. Always use this switch when compiling Ada programs.

Note: for some other languages when using gcc, notably in the case of C and C++, it is possible to use use gcc without a `-c' switch to compile and link in one step. In the case of GNAT, you cannot use this approach, because the binder must be run and gcc cannot be used to run the GNAT binder.

`-fno-inline'
Suppresses all back-end inlining, even if other optimization or inlining switches are set. This includes suppression of inlining that results from the use of the pragma Inline_Always. See also `-gnatn' and `-gnatN'.

`-fno-strict-aliasing'
Causes the compiler to avoid assumptions regarding non-aliasing of objects of different types. See 7.1.6 Optimization and Strict Aliasing for details.

`-fstack-check'
Activates stack checking. See 3.2.7 Stack Overflow Checking for details of the use of this option.

`-fstack-usage'
Makes the compiler output stack usage information for the program, on a per-function basis. The description of the format is to be found in the GCC documentation.

`-fcallgraph-info'
Makes the compiler output callgraph information for the program, on a per-file basis. The information is generated in the VCG format. It can be decorated with additional, per-node information if other debugging options are enabled (only works with -fstack-usage as of this writing).

`-g'
Generate debugging information. This information is stored in the object file and copied from there to the final executable file by the linker, where it can be read by the debugger. You must use the `-g' switch if you plan on using the debugger.

`-gnat83'
Enforce Ada 83 restrictions.

`-gnat95'
Enforce Ada 95 restrictions.

`-gnat05'
Allow full Ada 2005 features.

`-gnata'
Assertions enabled. Pragma Assert and pragma Debug to be activated.

`-gnatA'
Avoid processing `gnat.adc'. If a gnat.adc file is present, it will be ignored.

`-gnatb'
Generate brief messages to `stderr' even if verbose mode set.

`-gnatc'
Check syntax and semantics only (no code generation attempted).

`-gnatd'
Specify debug options for the compiler. The string of characters after the `-gnatd' specify the specific debug options. The possible characters are 0-9, a-z, A-Z, optionally preceded by a dot. See compiler source file `debug.adb' for details of the implemented debug options. Certain debug options are relevant to applications programmers, and these are documented at appropriate points in this users guide.

`-gnatD'
Create expanded source files for source level debugging. This switch also suppress generation of cross-reference information (see `-gnatx').

`-gnatec=path'
Specify a configuration pragma file (the equal sign is optional) (see section 9.2 The Configuration Pragmas Files).

`-gnateDsymbol[=value]'
Defines a symbol, associated with value, for preprocessing. (see section 3.2.18 Integrated Preprocessing).

`-gnatef'
Display full source path name in brief error messages.

`-gnatem=path'
Specify a mapping file (the equal sign is optional) (see section 3.2.17 Units to Sources Mapping Files).

`-gnatep=file'
Specify a preprocessing data file (the equal sign is optional) (see section 3.2.18 Integrated Preprocessing).

`-gnatE'
Full dynamic elaboration checks.

`-gnatf'
Full errors. Multiple errors per line, all undefined references, do not attempt to suppress cascaded errors.

`-gnatF'
Externals names are folded to all uppercase.

`-gnatg'
Internal GNAT implementation mode. This should not be used for applications programs, it is intended only for use by the compiler and its run-time library. For documentation, see the GNAT sources. Note that `-gnatg' implies `-gnatwu' so that warnings are generated on unreferenced entities, and all warnings are treated as errors.

`-gnatG'
List generated expanded code in source form.

`-gnath'
Output usage information. The output is written to `stdout'.

`-gnatic'
Identifier character set (c=1/2/3/4/8/9/p/f/n/w).

`-gnatk=n'
Limit file names to n (1-999) characters (k = krunch).

`-gnatl'
Output full source listing with embedded error messages.

`-gnatL'
This switch is deprecated. You can use `--RTS=sjlj' instead to enable setjmp/longjmp exception mechanism.

`-gnatm=n'
Limit number of detected error or warning messages to n where n is in the range 1..999_999. The default setting if no switch is given is 9999. Compilation is terminated if this limit is exceeded.

`-gnatn'
Activate inlining for subprograms for which pragma inline is specified. This inlining is performed by the GCC back-end.

`-gnatN'
Activate front end inlining for subprograms for which pragma Inline is specified. This inlining is performed by the front end and will be visible in the `-gnatG' output. In some cases, this has proved more effective than the back end inlining resulting from the use of `-gnatn'. Note that `-gnatN' automatically implies `-gnatn' so it is not necessary to specify both options. There are a few cases that the back-end inlining catches that cannot be dealt with in the front-end.

`-gnato'
Enable numeric overflow checking (which is not normally enabled by default). Not that division by zero is a separate check that is not controlled by this switch (division by zero checking is on by default).

`-gnatp'
Suppress all checks.

`-gnatP'
Enable polling. This is required on some systems (notably Windows NT) to obtain asynchronous abort and asynchronous transfer of control capability. See the description of pragma Polling in the GNAT Reference Manual for full details.

`-gnatq'
Don't quit; try semantics, even if parse errors.

`-gnatQ'
Don't quit; generate `ALI' and tree files even if illegalities.

`-gnatR[0/1/2/3[s]]'
Output representation information for declared types and objects.

`-gnats'
Syntax check only.

`-gnatS'
Print package Standard.

`-gnatt'
Generate tree output file.

`-gnatTnnn'
All compiler tables start at nnn times usual starting size.

`-gnatu'
List units for this compilation.

`-gnatU'
Tag all error messages with the unique string "error:"

`-gnatv'
Verbose mode. Full error output with source lines to `stdout'.

`-gnatV'
Control level of validity checking. See separate section describing this feature.

`-gnatwxxx'
Warning mode where xxx is a string of option letters that denotes the exact warnings that are enabled or disabled (see section 3.2.2 Warning Message Control).

`-gnatWe'
Wide character encoding method (e=n/h/u/s/e/8).

`-gnatx'
Suppress generation of cross-reference information.

`-gnaty'
Enable built-in style checks (see section 3.2.5 Style Checking).

`-gnatzm'
Distribution stub generation and compilation (m=r/c for receiver/caller stubs).

`-gnatZ'
This switch is deprecated. When zero cost exception handling is not the default and this is supported, you can use `--RTS=zcx' instead.

`-Idir'
Direct GNAT to search the dir directory for source files needed by the current compilation (see section 3.3 Search Paths and the Run-Time Library (RTL)).

`-I-'
Except for the source file named in the command line, do not look for source files in the directory containing the source file named in the command line (see section 3.3 Search Paths and the Run-Time Library (RTL)).

`-mbig-switch'
This standard gcc switch causes the compiler to use larger offsets in its jump table representation for case statements. This may result in less efficient code, but is sometimes necessary (for example on HP-UX targets) in order to compile large and/or nested case statements.

`-o file'
This switch is used in gcc to redirect the generated object file and its associated ALI file. Beware of this switch with GNAT, because it may cause the object file and ALI file to have different names which in turn may confuse the binder and the linker.

`-nostdinc'
Inhibit the search of the default location for the GNAT Run Time Library (RTL) source files.

`-nostdlib'
Inhibit the search of the default location for the GNAT Run Time Library (RTL) ALI files.

`-O[n]'
n controls the optimization level.

n = 0
No optimization, the default setting if no `-O' appears

n = 1
Normal optimization, the default if you specify `-O' without an operand.

n = 2
Extensive optimization

n = 3
Extensive optimization with automatic inlining of subprograms not specified by pragma Inline. This applies only to inlining within a unit. For details on control of inlining see 3.2.13 Subprogram Inlining Control.

`-pass-exit-codes'
Catch exit codes from the compiler and use the most meaningful as exit status.

`--RTS=rts-path'
Specifies the default location of the runtime library. Same meaning as the equivalent gnatmake flag (see section 6.2 Switches for gnatmake).

`-S'
Used in place of `-c' to cause the assembler source file to be generated, using `.s' as the extension, instead of the object file. This may be useful if you need to examine the generated assembly code.

`-fverbose-asm'
Used in conjunction with `-S' to cause the generated assembly code file to be annotated with variable names, making it significantly easier to follow.

`-v'
Show commands generated by the gcc driver. Normally used only for debugging purposes or if you need to be sure what version of the compiler you are executing.

`-V ver'
Execute ver version of the compiler. This is the gcc version, not the GNAT version.

You may combine a sequence of GNAT switches into a single switch. For example, the combined switch

 
-gnatofi3

is equivalent to specifying the following sequence of switches:

 
-gnato -gnatf -gnati3

The following restrictions apply to the combination of switches in this manner:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.1 Output and Error Message Control

The standard default format for error messages is called "brief format". Brief format messages are written to `stderr' (the standard error file) and have the following form:

 
e.adb:3:04: Incorrect spelling of keyword "function"
e.adb:4:20: ";" should be "is"

The first integer after the file name is the line number in the file, and the second integer is the column number within the line. glide can parse the error messages and point to the referenced character. The following switches provide control over the error message format:

`-gnatv'
The v stands for verbose. The effect of this setting is to write long-format error messages to `stdout' (the standard output file. The same program compiled with the `-gnatv' switch would generate:

 
3. funcion X (Q : Integer)
   |
>>> Incorrect spelling of keyword "function"
4. return Integer;
                 |
>>> ";" should be "is"

The vertical bar indicates the location of the error, and the `>>>' prefix can be used to search for error messages. When this switch is used the only source lines output are those with errors.

`-gnatl'
The l stands for list. This switch causes a full listing of the file to be generated. The output might look as follows:

 
 1. procedure E is
 2.    V : Integer;
 3.    funcion X (Q : Integer)
       |
    >>> Incorrect spelling of keyword "function"
 4.     return Integer;
                      |
    >>> ";" should be "is"
 5.    begin
 6.       return Q + Q;
 7.    end;
 8. begin
 9.    V := X + X;
10.end E;

When you specify the `-gnatv' or `-gnatl' switches and standard output is redirected, a brief summary is written to `stderr' (standard error) giving the number of error messages and warning messages generated.

`-gnatU'
This switch forces all error messages to be preceded by the unique string "error:". This means that error messages take a few more characters in space, but allows easy searching for and identification of error messages.

`-gnatb'
The b stands for brief. This switch causes GNAT to generate the brief format error messages to `stderr' (the standard error file) as well as the verbose format message or full listing (which as usual is written to `stdout' (the standard output file).

`-gnatmn'
The m stands for maximum. n is a decimal integer in the range of 1 to 999 and limits the number of error messages to be generated. For example, using `-gnatm2' might yield

 
e.adb:3:04: Incorrect spelling of keyword "function"
e.adb:5:35: missing ".."
fatal error: maximum errors reached
compilation abandoned

`-gnatf'
The f stands for full. Normally, the compiler suppresses error messages that are likely to be redundant. This switch causes all error messages to be generated. In particular, in the case of references to undefined variables. If a given variable is referenced several times, the normal format of messages is
 
e.adb:7:07: "V" is undefined (more references follow)

where the parenthetical comment warns that there are additional references to the variable V. Compiling the same program with the `-gnatf' switch yields

 
e.adb:7:07: "V" is undefined
e.adb:8:07: "V" is undefined
e.adb:8:12: "V" is undefined
e.adb:8:16: "V" is undefined
e.adb:9:07: "V" is undefined
e.adb:9:12: "V" is undefined

The `-gnatf' switch also generates additional information for some error messages. Some examples are:

`-gnatq'
The q stands for quit (really "don't quit"). In normal operation mode, the compiler first parses the program and determines if there are any syntax errors. If there are, appropriate error messages are generated and compilation is immediately terminated. This switch tells GNAT to continue with semantic analysis even if syntax errors have been found. This may enable the detection of more errors in a single run. On the other hand, the semantic analyzer is more likely to encounter some internal fatal error when given a syntactically invalid tree.

`-gnatQ'
In normal operation mode, the `ALI' file is not generated if any illegalities are detected in the program. The use of `-gnatQ' forces generation of the `ALI' file. This file is marked as being in error, so it cannot be used for binding purposes, but it does contain reasonably complete cross-reference information, and thus may be useful for use by tools (e.g. semantic browsing tools or integrated development environments) that are driven from the `ALI' file. This switch implies `-gnatq', since the semantic phase must be run to get a meaningful ALI file.

In addition, if `-gnatt' is also specified, then the tree file is generated even if there are illegalities. It may be useful in this case to also specify `-gnatq' to ensure that full semantic processing occurs. The resulting tree file can be processed by ASIS, for the purpose of providing partial information about illegal units, but if the error causes the tree to be badly malformed, then ASIS may crash during the analysis.

When `-gnatQ' is used and the generated `ALI' file is marked as being in error, gnatmake will attempt to recompile the source when it finds such an `ALI' file, including with switch `-gnatc'.

Note that `-gnatQ' has no effect if `-gnats' is specified, since ALI files are never generated if `-gnats' is set.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.2 Warning Message Control

In addition to error messages, which correspond to illegalities as defined in the Ada 95 Reference Manual, the compiler detects two kinds of warning situations.

First, the compiler considers some constructs suspicious and generates a warning message to alert you to a possible error. Second, if the compiler detects a situation that is sure to raise an exception at run time, it generates a warning message. The following shows an example of warning messages:
 
e.adb:4:24: warning: creation of object may raise Storage_Error
e.adb:10:17: warning: static value out of range
e.adb:10:17: warning: "Constraint_Error" will be raised at run time

GNAT considers a large number of situations as appropriate for the generation of warning messages. As always, warnings are not definite indications of errors. For example, if you do an out-of-range assignment with the deliberate intention of raising a Constraint_Error exception, then the warning that may be issued does not indicate an error. Some of the situations for which GNAT issues warnings (at least some of the time) are given in the following list. This list is not complete, and new warnings are often added to subsequent versions of GNAT. The list is intended to give a general idea of the kinds of warnings that are generated.

The following switches are available to control the handling of warning messages:

`-gnatwa'
Activate all optional errors. This switch activates most optional warning messages, see remaining list in this section for details on optional warning messages that can be individually controlled. The warnings that are not turned on by this switch are `-gnatwd' (implicit dereferencing), `-gnatwh' (hiding), and `-gnatwl' (elaboration warnings). All other optional warnings are turned on.

`-gnatwA'
Suppress all optional errors. This switch suppresses all optional warning messages, see remaining list in this section for details on optional warning messages that can be individually controlled.

`-gnatwb'
Activate warnings on bad fixed values. This switch activates warnings for static fixed-point expressions whose value is not an exact multiple of Small. Such values are implementation dependent, since an implementation is free to choose either of the multiples that surround the value. GNAT always chooses the closer one, but this is not required behavior, and it is better to specify a value that is an exact multiple, ensuring predictable execution. The default is that such warnings are not generated.

`-gnatwB'
Suppress warnings on bad fixed values. This switch suppresses warnings for static fixed-point expressions whose value is not an exact multiple of Small.

`-gnatwc'
Activate warnings on conditionals. This switch activates warnings for conditional expressions used in tests that are known to be True or False at compile time. The default is that such warnings are not generated. Note that this warning does not get issued for the use of boolean variables or constants whose values are known at compile time, since this is a standard technique for conditional compilation in Ada, and this would generate too many "false positive" warnings. This warning can also be turned on using `-gnatwa'.

`-gnatwC'
Suppress warnings on conditionals. This switch suppresses warnings for conditional expressions used in tests that are known to be True or False at compile time.

`-gnatwd'
Activate warnings on implicit dereferencing. If this switch is set, then the use of a prefix of an access type in an indexed component, slice, or selected component without an explicit .all will generate a warning. With this warning enabled, access checks occur only at points where an explicit .all appears in the source code (assuming no warnings are generated as a result of this switch). The default is that such warnings are not generated. Note that `-gnatwa' does not affect the setting of this warning option.

`-gnatwD'
Suppress warnings on implicit dereferencing. This switch suppresses warnings for implicit dereferences in indexed components, slices, and selected components.

`-gnatwe'
Treat warnings as errors. This switch causes warning messages to be treated as errors. The warning string still appears, but the warning messages are counted as errors, and prevent the generation of an object file.

`-gnatwf'
Activate warnings on unreferenced formals. This switch causes a warning to be generated if a formal parameter is not referenced in the body of the subprogram. This warning can also be turned on using `-gnatwa' or `-gnatwu'.

`-gnatwF'
Suppress warnings on unreferenced formals. This switch suppresses warnings for unreferenced formal parameters. Note that the combination `-gnatwu' followed by `-gnatwF' has the effect of warning on unreferenced entities other than subprogram formals.

`-gnatwg'
Activate warnings on unrecognized pragmas. This switch causes a warning to be generated if an unrecognized pragma is encountered. Apart from issuing this warning, the pragma is ignored and has no effect. This warning can also be turned on using `-gnatwa'. The default is that such warnings are issued (satisfying the Ada Reference Manual requirement that such warnings appear).

`-gnatwG'
Suppress warnings on unrecognized pragmas. This switch suppresses warnings for unrecognized pragmas.

`-gnatwh'
Activate warnings on hiding. This switch activates warnings on hiding declarations. A declaration is considered hiding if it is for a non-overloadable entity, and it declares an entity with the same name as some other entity that is directly or use-visible. The default is that such warnings are not generated. Note that `-gnatwa' does not affect the setting of this warning option.

`-gnatwH'
Suppress warnings on hiding. This switch suppresses warnings on hiding declarations.

`-gnatwi'
Activate warnings on implementation units. This switch activates warnings for a with of an internal GNAT implementation unit, defined as any unit from the Ada, Interfaces, GNAT, or System hierarchies that is not documented in either the Ada Reference Manual or the GNAT Programmer's Reference Manual. Such units are intended only for internal implementation purposes and should not be with'ed by user programs. The default is that such warnings are generated This warning can also be turned on using `-gnatwa'.

`-gnatwI'
Disable warnings on implementation units. This switch disables warnings for a with of an internal GNAT implementation unit.

`-gnatwj'
Activate warnings on obsolescent features (Annex J). If this warning option is activated, then warnings are generated for calls to subprograms marked with pragma Obsolescent and for use of features in Annex J of the Ada Reference Manual. In the case of Annex J, not all features are flagged. In particular use of the renamed packages (like Text_IO) and use of package ASCII are not flagged, since these are very common and would generate many annoying positive warnings. The default is that such warnings are not generated.

In addition to the above cases, warnings are also generated for GNAT features that have been provided in past versions but which have been superceded (typically by features in the new Ada standard). For example, pragma Ravenscar will be flagged since its function is replaced by pragma Profile(Ravenscar).

Note that this warning option functions differently from the restriction No_Obsolescent_Features in two respects. First, the restriction applies only to annex J features. Second, the restriction does flag uses of package ASCII.

`-gnatwJ'
Suppress warnings on obsolescent features (Annex J). This switch disables warnings on use of obsolescent features.

`-gnatwk'
Activate warnings on variables that could be constants. This switch activates warnings for variables that are initialized but never modified, and then could be declared constants.

`-gnatwK'
Suppress warnings on variables that could be constants. This switch disables warnings on variables that could be declared constants.

`-gnatwl'
Activate warnings for missing elaboration pragmas. This switch activates warnings on missing pragma Elaborate_All statements. See the section in this guide on elaboration checking for details on when such pragma should be used. Warnings are also generated if you are using the static mode of elaboration, and a pragma Elaborate is encountered. The default is that such warnings are not generated. This warning is not automatically turned on by the use of `-gnatwa'.

`-gnatwL'
Suppress warnings for missing elaboration pragmas. This switch suppresses warnings on missing pragma Elaborate_All statements. See the section in this guide on elaboration checking for details on when such pragma should be used.

`-gnatwm'
Activate warnings on modified but unreferenced variables. This switch activates warnings for variables that are assigned (using an initialization value or with one or more assignment statements) but whose value is never read. The warning is suppressed for volatile variables and also for variables that are renamings of other variables or for which an address clause is given. This warning can also be turned on using `-gnatwa'.

`-gnatwM'
Disable warnings on modified but unreferenced variables. This switch disables warnings for variables that are assigned or initialized, but never read.

`-gnatwn'
Set normal warnings mode. This switch sets normal warning mode, in which enabled warnings are issued and treated as warnings rather than errors. This is the default mode. the switch `-gnatwn' can be used to cancel the effect of an explicit `-gnatws' or `-gnatwe'. It also cancels the effect of the implicit `-gnatwe' that is activated by the use of `-gnatg'.

`-gnatwo'
Activate warnings on address clause overlays. This switch activates warnings for possibly unintended initialization effects of defining address clauses that cause one variable to overlap another. The default is that such warnings are generated. This warning can also be turned on using `-gnatwa'.

`-gnatwO'
Suppress warnings on address clause overlays. This switch suppresses warnings on possibly unintended initialization effects of defining address clauses that cause one variable to overlap another.

`-gnatwp'
Activate warnings on ineffective pragma Inlines. This switch activates warnings for failure of front end inlining (activated by `-gnatN') to inline a particular call. There are many reasons for not being able to inline a call, including most commonly that the call is too complex to inline. This warning can also be turned on using `-gnatwa'.

`-gnatwP'
Suppress warnings on ineffective pragma Inlines. This switch suppresses warnings on ineffective pragma Inlines. If the inlining mechanism cannot inline a call, it will simply ignore the request silently.

`-gnatwr'
Activate warnings on redundant constructs. This switch activates warnings for redundant constructs. The following is the current list of constructs regarded as redundant: This warning can also be turned on using `-gnatwa'.

`-gnatwR'
Suppress warnings on redundant constructs. This switch suppresses warnings for redundant constructs.

`-gnatws'
Suppress all warnings. This switch completely suppresses the output of all warning messages from the GNAT front end. Note that it does not suppress warnings from the gcc back end. To suppress these back end warnings as well, use the switch `-w' in addition to `-gnatws'.

`-gnatwu'
Activate warnings on unused entities. This switch activates warnings to be generated for entities that are declared but not referenced, and for units that are with'ed and not referenced. In the case of packages, a warning is also generated if no entities in the package are referenced. This means that if the package is referenced but the only references are in use clauses or renames declarations, a warning is still generated. A warning is also generated for a generic package that is with'ed but never instantiated. In the case where a package or subprogram body is compiled, and there is a with on the corresponding spec that is only referenced in the body, a warning is also generated, noting that the with can be moved to the body. The default is that such warnings are not generated. This switch also activates warnings on unreferenced formals (it includes the effect of `-gnatwf'). This warning can also be turned on using `-gnatwa'.

`-gnatwU'
Suppress warnings on unused entities. This switch suppresses warnings for unused entities and packages. It also turns off warnings on unreferenced formals (and thus includes the effect of `-gnatwF').

`-gnatwv'
Activate warnings on unassigned variables. This switch activates warnings for access to variables which may not be properly initialized. The default is that such warnings are generated.

`-gnatwV'
Suppress warnings on unassigned variables. This switch suppresses warnings for access to variables which may not be properly initialized.

`-gnatwx'
Activate warnings on Export/Import pragmas. This switch activates warnings on Export/Import pragmas when the compiler detects a possible conflict between the Ada and foreign language calling sequences. For example, the use of default parameters in a convention C procedure is dubious because the C compiler cannot supply the proper default, so a warning is issued. The default is that such warnings are generated.

`-gnatwX'
Suppress warnings on Export/Import pragmas. This switch suppresses warnings on Export/Import pragmas. The sense of this is that you are telling the compiler that you know what you are doing in writing the pragma, and it should not complain at you.

`-gnatwz'
Activate warnings on unchecked conversions. This switch activates warnings for unchecked conversions where the types are known at compile time to have different sizes. The default is that such warnings are generated.

`-gnatwZ'
Suppress warnings on unchecked conversions. This switch suppresses warnings for unchecked conversions where the types are known at compile time to have different sizes.

`-Wuninitialized'
The warnings controlled by the `-gnatw' switch are generated by the front end of the compiler. In some cases, the `gcc' back end can provide additional warnings. One such useful warning is provided by `-Wuninitialized'. This must be used in conjunction with tunrning on optimization mode. This causes the flow analysis circuits of the back end optimizer to output additional warnings about uninitialized variables.

`-w'
This switch suppresses warnings from the `gcc' back end. It may be used in conjunction with `-gnatws' to ensure that all warnings are suppressed during the entire compilation process.

A string of warning parameters can be used in the same parameter. For example:

 
-gnatwaLe

will turn on all optional warnings except for elaboration pragma warnings, and also specify that warnings should be treated as errors. When no switch `-gnatw' is used, this is equivalent to:

`-gnatwC'
`-gnatwD'
`-gnatwF'
`-gnatwg'
`-gnatwH'
`-gnatwi'
`-gnatwJ'
`-gnatwK'
`-gnatwL'
`-gnatwM'
`-gnatwn'
`-gnatwo'
`-gnatwP'
`-gnatwR'
`-gnatwU'
`-gnatwv'
`-gnatwz'
`-gnatwx'


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.3 Debugging and Assertion Control

`-gnata'

The pragmas Assert and Debug normally have no effect and are ignored. This switch, where `a' stands for assert, causes Assert and Debug pragmas to be activated.

The pragmas have the form:

 
   pragma Assert (Boolean-expression [,
                      static-string-expression])
   pragma Debug (procedure call)

The Assert pragma causes Boolean-expression to be tested. If the result is True, the pragma has no effect (other than possible side effects from evaluating the expression). If the result is False, the exception Assert_Failure declared in the package System.Assertions is raised (passing static-string-expression, if present, as the message associated with the exception). If no string expression is given the default is a string giving the file name and line number of the pragma.

The Debug pragma causes procedure to be called. Note that pragma Debug may appear within a declaration sequence, allowing debugging procedures to be called between declarations.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.4 Validity Checking

The Ada 95 Reference Manual has specific requirements for checking for invalid values. In particular, RM 13.9.1 requires that the evaluation of invalid values (for example from unchecked conversions), not result in erroneous execution. In GNAT, the result of such an evaluation in normal default mode is to either use the value unmodified, or to raise Constraint_Error in those cases where use of the unmodified value would cause erroneous execution. The cases where unmodified values might lead to erroneous execution are case statements (where a wild jump might result from an invalid value), and subscripts on the left hand side (where memory corruption could occur as a result of an invalid value).

The `-gnatVx' switch allows more control over the validity checking mode. The x argument is a string of letters that indicate validity checks that are performed or not performed in addition to the default checks described above.

`-gnatVa'
All validity checks. All validity checks are turned on. That is, `-gnatVa' is equivalent to `gnatVcdfimorst'.

`-gnatVc'
Validity checks for copies. The right hand side of assignments, and the initializing values of object declarations are validity checked.

`-gnatVd'
Default (RM) validity checks. Some validity checks are done by default following normal Ada semantics (RM 13.9.1 (9-11)). A check is done in case statements that the expression is within the range of the subtype. If it is not, Constraint_Error is raised. For assignments to array components, a check is done that the expression used as index is within the range. If it is not, Constraint_Error is raised. Both these validity checks may be turned off using switch `-gnatVD'. They are turned on by default. If `-gnatVD' is specified, a subsequent switch `-gnatVd' will leave the checks turned on. Switch `-gnatVD' should be used only if you are sure that all such expressions have valid values. If you use this switch and invalid values are present, then the program is erroneous, and wild jumps or memory overwriting may occur.

`-gnatVf'
Validity checks for floating-point values. In the absence of this switch, validity checking occurs only for discrete values. If `-gnatVf' is specified, then validity checking also applies for floating-point values, and NaN's and infinities are considered invalid, as well as out of range values for constrained types. Note that this means that standard IEEE infinity mode is not allowed. The exact contexts in which floating-point values are checked depends on the setting of other options. For example, `-gnatVif' or `-gnatVfi' (the order does not matter) specifies that floating-point parameters of mode in should be validity checked.

`-gnatVi'
Validity checks for in mode parameters Arguments for parameters of mode in are validity checked in function and procedure calls at the point of call.

`-gnatVm'
Validity checks for in out mode parameters. Arguments for parameters of mode in out are validity checked in procedure calls at the point of call. The 'm' here stands for modify, since this concerns parameters that can be modified by the call. Note that there is no specific option to test out parameters, but any reference within the subprogram will be tested in the usual manner, and if an invalid value is copied back, any reference to it will be subject to validity checking.

`-gnatVn'
No validity checks. This switch turns off all validity checking, including the default checking for case statements and left hand side subscripts. Note that the use of the switch `-gnatp' suppresses all run-time checks, including validity checks, and thus implies `-gnatVn'. When this switch is used, it cancels any other `-gnatV' previously issued.

`-gnatVo'
Validity checks for operator and attribute operands. Arguments for predefined operators and attributes are validity checked. This includes all operators in package Standard, the shift operators defined as intrinsic in package Interfaces and operands for attributes such as Pos. Checks are also made on individual component values for composite comparisons.

`-gnatVp'
Validity checks for parameters. This controls the treatment of parameters within a subprogram (as opposed to `-gnatVi' and `-gnatVm' which control validity testing of parameters on a call. If either of these call options is used, then normally an assumption is made within a subprogram that the input arguments have been validity checking at the point of call, and do not need checking again within a subprogram). If `-gnatVp' is set, then this assumption is not made, and parameters are not assumed to be valid, so their validity will be checked (or rechecked) within the subprogram.

`-gnatVr'
Validity checks for function returns. The expression in return statements in functions is validity checked.

`-gnatVs'
Validity checks for subscripts. All subscripts expressions are checked for validity, whether they appear on the right side or left side (in default mode only left side subscripts are validity checked).

`-gnatVt'
Validity checks for tests. Expressions used as conditions in if, while or exit statements are checked, as well as guard expressions in entry calls.

The `-gnatV' switch may be followed by a string of letters to turn on a series of validity checking options. For example, `-gnatVcr' specifies that in addition to the default validity checking, copies and function return expressions are to be validity checked. In order to make it easier to specify the desired combination of effects, the upper case letters CDFIMORST may be used to turn off the corresponding lower case option. Thus `-gnatVaM' turns on all validity checking options except for checking of in out procedure arguments.

The specification of additional validity checking generates extra code (and in the case of `-gnatVa' the code expansion can be substantial. However, these additional checks can be very useful in detecting uninitialized variables, incorrect use of unchecked conversion, and other errors leading to invalid values. The use of pragma Initialize_Scalars is useful in conjunction with the extra validity checking, since this ensures that wherever possible uninitialized variables have invalid values.

See also the pragma Validity_Checks which allows modification of the validity checking mode at the program source level, and also allows for temporary disabling of validity checks.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.5 Style Checking

The `-gnatyx' switch causes the compiler to enforce specified style rules. A limited set of style rules has been used in writing the GNAT sources themselves. This switch allows user programs to activate all or some of these checks. If the source program fails a specified style check, an appropriate warning message is given, preceded by the character sequence "(style)". The string x is a sequence of letters or digits indicating the particular style checks to be performed. The following checks are defined:

`1-9'
Specify indentation level. If a digit from 1-9 appears in the string after `-gnaty' then proper indentation is checked, with the digit indicating the indentation level required. The general style of required indentation is as specified by the examples in the Ada Reference Manual. Full line comments must be aligned with the -- starting on a column that is a multiple of the alignment level.

`a'
Check attribute casing. If the letter a appears in the string after `-gnaty' then attribute names, including the case of keywords such as digits used as attributes names, must be written in mixed case, that is, the initial letter and any letter following an underscore must be uppercase. All other letters must be lowercase.

`b'
Blanks not allowed at statement end. If the letter b appears in the string after `-gnaty' then trailing blanks are not allowed at the end of statements. The purpose of this rule, together with h (no horizontal tabs), is to enforce a canonical format for the use of blanks to separate source tokens.

`c'
Check comments. If the letter c appears in the string after `-gnaty' then comments must meet the following set of rules:

`d'
Check no DOS line terminators present. If the letter d appears in the string after `-gnaty' then all lines must be terminated by a single ASCII.LF character (in particular the DOS line terminator sequence CR/LF is not allowed).

`e'
Check end/exit labels. If the letter e appears in the string after `-gnaty' then optional labels on end statements ending subprograms and on exit statements exiting named loops, are required to be present.

`f'
No form feeds or vertical tabs. If the letter f appears in the string after `-gnaty' then neither form feeds nor vertical tab characters are permitted in the source text.

`h'
No horizontal tabs. If the letter h appears in the string after `-gnaty' then horizontal tab characters are not permitted in the source text. Together with the b (no blanks at end of line) check, this enforces a canonical form for the use of blanks to separate source tokens.

`i'
Check if-then layout. If the letter i appears in the string after `-gnaty', then the keyword then must appear either on the same line as corresponding if, or on a line on its own, lined up under the if with at least one non-blank line in between containing all or part of the condition to be tested.

`k'
Check keyword casing. If the letter k appears in the string after `-gnaty' then all keywords must be in lower case (with the exception of keywords such as digits used as attribute names to which this check does not apply).

`l'
Check layout. If the letter l appears in the string after `-gnaty' then layout of statement and declaration constructs must follow the recommendations in the Ada Reference Manual, as indicated by the form of the syntax rules. For example an else keyword must be lined up with the corresponding if keyword.

There are two respects in which the style rule enforced by this check option are more liberal than those in the Ada Reference Manual. First in the case of record declarations, it is permissible to put the record keyword on the same line as the type keyword, and then the end in end record must line up under type. For example, either of the following two layouts is acceptable:

 
type q is record
   a : integer;
   b : integer;
end record;

type q is
   record
      a : integer;
      b : integer;
   end record;

Second, in the case of a block statement, a permitted alternative is to put the block label on the same line as the declare or begin keyword, and then line the end keyword up under the block label. For example both the following are permitted:

 
Block : declare
   A : Integer := 3;
begin
   Proc (A, A);
end Block;

Block :
   declare
      A : Integer := 3;
   begin
      Proc (A, A);
   end Block;

The same alternative format is allowed for loops. For example, both of the following are permitted:

 
Clear : while J < 10 loop
   A (J) := 0;
end loop Clear;

Clear :
   while J < 10 loop
      A (J) := 0;
   end loop Clear;

`Lnnn'
Set maximum nesting level If the sequence Lnnn, where nnn is a decimal number in the range 0-999, appears in the string after `-gnaty' then the maximum level of nesting of constructs (including subprograms, loops, blocks, packages, and conditionals) may not exceed the given value. A value of zero disconnects this style check.

`m'
Check maximum line length. If the letter m appears in the string after `-gnaty' then the length of source lines must not exceed 79 characters, including any trailing blanks. The value of 79 allows convenient display on an 80 character wide device or window, allowing for possible special treatment of 80 character lines. Note that this count is of raw characters in the source text. This means that a tab character counts as one character in this count and a wide character sequence counts as several characters (however many are needed in the encoding).

`Mnnn'
Set maximum line length. If the sequence Mnnn, where nnn is a decimal number, appears in the string after `-gnaty' then the length of lines must not exceed the given value.

`n'
Check casing of entities in Standard. If the letter n appears in the string after `-gnaty' then any identifier from Standard must be cased to match the presentation in the Ada Reference Manual (for example, Integer and ASCII.NUL).

`o'
Check order of subprogram bodies. If the letter o appears in the string after `-gnaty' then all subprogram bodies in a given scope (e.g. a package body) must be in alphabetical order. The ordering rule uses normal Ada rules for comparing strings, ignoring casing of letters, except that if there is a trailing numeric suffix, then the value of this suffix is used in the ordering (e.g. Junk2 comes before Junk10).

`p'
Check pragma casing. If the letter p appears in the string after `-gnaty' then pragma names must be written in mixed case, that is, the initial letter and any letter following an underscore must be uppercase. All other letters must be lowercase.

`r'
Check references. If the letter r appears in the string after `-gnaty' then all identifier references must be cased in the same way as the corresponding declaration. No specific casing style is imposed on identifiers. The only requirement is for consistency of references with declarations.

`s'
Check separate specs. If the letter s appears in the string after `-gnaty' then separate declarations ("specs") are required for subprograms (a body is not allowed to serve as its own declaration). The only exception is that parameterless library level procedures are not required to have a separate declaration. This exception covers the most frequent form of main program procedures.

`t'
Check token spacing. If the letter t appears in the string after `-gnaty' then the following token spacing rules are enforced:

`u'
Check unnecessary blank lines. Check for unnecessary blank lines. A blank line is considered unnecessary if it appears at the end of the file, or if more than one blank line occurs in sequence.

`x'
Check extra parentheses. Check for the use of an unnecessary extra level of parentheses (C-style) around conditions in if statements, while statements and exit statements.

In the above rules, appearing in column one is always permitted, that is, counts as meeting either a requirement for a required preceding space, or as meeting a requirement for no preceding space.

Appearing at the end of a line is also always permitted, that is, counts as meeting either a requirement for a following space, or as meeting a requirement for no following space.

If any of these style rules is violated, a message is generated giving details on the violation. The initial characters of such messages are always "(style)". Note that these messages are treated as warning messages, so they normally do not prevent the generation of an object file. The `-gnatwe' switch can be used to treat warning messages, including style messages, as fatal errors.

The switch `-gnaty' on its own (that is not followed by any letters or digits), is equivalent to gnaty3abcefhiklmnprst, that is all checking options enabled with the exception of `-gnatyo', `-gnatyd', `-gnatyu', and `-gnatyx'. an indentation level of 3 is set. This is similar to the standard checking option that is used for the GNAT sources.

The switch `-gnatyN' clears any previously set style checks.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.6 Run-Time Checks

If you compile with the default options, GNAT will insert many run-time checks into the compiled code, including code that performs range checking against constraints, but not arithmetic overflow checking for integer operations (including division by zero) or checks for access before elaboration on subprogram calls. All other run-time checks, as required by the Ada 95 Reference Manual, are generated by default. The following gcc switches refine this default behavior:

`-gnatp'
Suppress all run-time checks as though pragma Suppress (all_checks) had been present in the source. Validity checks are also suppressed (in other words `-gnatp' also implies `-gnatVn'. Use this switch to improve the performance of the code at the expense of safety in the presence of invalid data or program bugs.

`-gnato'
Enables overflow checking for integer operations. This causes GNAT to generate slower and larger executable programs by adding code to check for overflow (resulting in raising Constraint_Error as required by standard Ada semantics). These overflow checks correspond to situations in which the true value of the result of an operation may be outside the base range of the result type. The following example shows the distinction:

 
X1 : Integer := Integer'Last;
X2 : Integer range 1 .. 5 := 5;
X3 : Integer := Integer'Last;
X4 : Integer range 1 .. 5 := 5;
F  : Float := 2.0E+20;
...
X1 := X1 + 1;
X2 := X2 + 1;
X3 := Integer (F);
X4 := Integer (F);

Here the first addition results in a value that is outside the base range of Integer, and hence requires an overflow check for detection of the constraint error. Thus the first assignment to X1 raises a Constraint_Error exception only if `-gnato' is set.

The second increment operation results in a violation of the explicit range constraint, and such range checks are always performed (unless specifically suppressed with a pragma suppress or the use of `-gnatp').

The two conversions of F both result in values that are outside the base range of type Integer and thus will raise Constraint_Error exceptions only if `-gnato' is used. The fact that the result of the second conversion is assigned to variable X4 with a restricted range is irrelevant, since the problem is in the conversion, not the assignment.

Basically the rule is that in the default mode (`-gnato' not used), the generated code assures that all integer variables stay within their declared ranges, or within the base range if there is no declared range. This prevents any serious problems like indexes out of range for array operations.

What is not checked in default mode is an overflow that results in an in-range, but incorrect value. In the above example, the assignments to X1, X2, X3 all give results that are within the range of the target variable, but the result is wrong in the sense that it is too large to be represented correctly. Typically the assignment to X1 will result in wrap around to the largest negative number. The conversions of F will result in some Integer value and if that integer value is out of the X4 range then the subsequent assignment would generate an exception.

Note that the `-gnato' switch does not affect the code generated for any floating-point operations; it applies only to integer semantics). For floating-point, GNAT has the Machine_Overflows attribute set to False and the normal mode of operation is to generate IEEE NaN and infinite values on overflow or invalid operations (such as dividing 0.0 by 0.0).

The reason that we distinguish overflow checking from other kinds of range constraint checking is that a failure of an overflow check can generate an incorrect value, but cannot cause erroneous behavior. This is unlike the situation with a constraint check on an array subscript, where failure to perform the check can result in random memory description, or the range check on a case statement, where failure to perform the check can cause a wild jump.

Note again that `-gnato' is off by default, so overflow checking is not performed in default mode. This means that out of the box, with the default settings, GNAT does not do all the checks expected from the language description in the Ada Reference Manual. If you want all constraint checks to be performed, as described in this Manual, then you must explicitly use the -gnato switch either on the gnatmake or gcc command.

`-gnatE'
Enables dynamic checks for access-before-elaboration on subprogram calls and generic instantiations. For full details of the effect and use of this switch, See section 3. Compiling Using gcc.

The setting of these switches only controls the default setting of the checks. You may modify them using either Suppress (to remove checks) or Unsuppress (to add back suppressed checks) pragmas in the program source.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.7 Stack Overflow Checking

For most operating systems, gcc does not perform stack overflow checking by default. This means that if the main environment task or some other task exceeds the available stack space, then unpredictable behavior will occur.

To activate stack checking, compile all units with the gcc option `-fstack-check'. For example:

 
gcc -c -fstack-check package1.adb

Units compiled with this option will generate extra instructions to check that any use of the stack (for procedure calls or for declaring local variables in declare blocks) do not exceed the available stack space. If the space is exceeded, then a Storage_Error exception is raised.

For declared tasks, the stack size is always controlled by the size given in an applicable Storage_Size pragma (or is set to the default size if no pragma is used.

For the environment task, the stack size depends on system defaults and is unknown to the compiler. The stack may even dynamically grow on some systems, precluding the normal Ada semantics for stack overflow. In the worst case, unbounded stack usage, causes unbounded stack expansion resulting in the system running out of virtual memory.

The stack checking may still work correctly if a fixed size stack is allocated, but this cannot be guaranteed. To ensure that a clean exception is signalled for stack overflow, set the environment variable GNAT_STACK_LIMIT to indicate the maximum stack area that can be used, as in:

 
SET GNAT_STACK_LIMIT 1600

The limit is given in kilobytes, so the above declaration would set the stack limit of the environment task to 1.6 megabytes. Note that the only purpose of this usage is to limit the amount of stack used by the environment task. If it is necessary to increase the amount of stack for the environment task, then this is an operating systems issue, and must be addressed with the appropriate operating systems commands.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.8 Using gcc for Syntax Checking

`-gnats'

The s stands for "syntax".

Run GNAT in syntax checking only mode. For example, the command

 
$ gcc -c -gnats x.adb

compiles file `x.adb' in syntax-check-only mode. You can check a series of files in a single command , and can use wild cards to specify such a group of files. Note that you must specify the `-c' (compile only) flag in addition to the `-gnats' flag. . You may use other switches in conjunction with `-gnats'. In particular, `-gnatl' and `-gnatv' are useful to control the format of any generated error messages.

When the source file is empty or contains only empty lines and/or comments, the output is a warning:

 
$ gcc -c -gnats -x ada toto.txt
toto.txt:1:01: warning: empty file, contains no compilation units
$

Otherwise, the output is simply the error messages, if any. No object file or ALI file is generated by a syntax-only compilation. Also, no units other than the one specified are accessed. For example, if a unit X with's a unit Y, compiling unit X in syntax check only mode does not access the source file containing unit Y.

Normally, GNAT allows only a single unit in a source file. However, this restriction does not apply in syntax-check-only mode, and it is possible to check a file containing multiple compilation units concatenated together. This is primarily used by the gnatchop utility (see section 8. Renaming Files Using gnatchop).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.9 Using gcc for Semantic Checking

`-gnatc'

The c stands for "check". Causes the compiler to operate in semantic check mode, with full checking for all illegalities specified in the Ada 95 Reference Manual, but without generation of any object code (no object file is generated).

Because dependent files must be accessed, you must follow the GNAT semantic restrictions on file structuring to operate in this mode:

The output consists of error messages as appropriate. No object file is generated. An `ALI' file is generated for use in the context of cross-reference tools, but this file is marked as not being suitable for binding (since no object file is generated). The checking corresponds exactly to the notion of legality in the Ada 95 Reference Manual.

Any unit can be compiled in semantics-checking-only mode, including units that would not normally be compiled (subunits, and specifications where a separate body is present).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.10 Compiling Different Versions of Ada

GNAT is primarily an Ada 95 compiler, but the switches described in this section allow operation in Ada 83 compatibility mode, and also allow the use of a preliminary implementation of many of the expected new features in Ada 2005, the forthcoming new version of the standard.
`-gnat83 (Ada 83 Compatibility Mode)'

Although GNAT is primarily an Ada 95 compiler, it accepts this switch to specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics where this can be done easily. It is not possible to guarantee this switch does a perfect job; for example, some subtle tests, such as are found in earlier ACVC tests (and that have been removed from the ACATS suite for Ada 95), might not compile correctly. Nevertheless, this switch may be useful in some circumstances, for example where, due to contractual reasons, legacy code needs to be maintained using only Ada 83 features.

With few exceptions (most notably the need to use <> on unconstrained generic formal parameters, the use of the new Ada 95 reserved words, and the use of packages with optional bodies), it is not necessary to use the `-gnat83' switch when compiling Ada 83 programs, because, with rare exceptions, Ada 95 is upwardly compatible with Ada 83. This means that a correct Ada 83 program is usually also a correct Ada 95 program. For further information, please refer to E. Compatibility and Porting Guide.

`-gnat95 (Ada 95 mode)'

GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards compatible with Ada 83, that legacy Ada 83 programs may be compiled using this default Ada95 mode without problems (see section above describing the use of `-gnat83' to run in Ada 83 mode).

In Ada 95 mode, the use of Ada 2005 features will in general cause error messages or warnings. Some specialized releases of GNAT (notably the GAP academic version) operate in Ada 2005 mode by default (see section below describing the use of `-gnat05' to run in Ada 2005 mode). For such versions the `-gnat95' switch may be used to enforce Ada 95 mode. This option also can be used to cancel the effect of a previous `-gnat83' or `-gnat05' switch earlier in the command line.

`-gnat05 (Ada 2005 mode)'

Although GNAT is primarily an Ada 95 compiler, it can be set to operate in Ada 2005 mode using this option. Although the new standard has not yet been issued (as of early 2005), many features have been discussed and approved in "Ada Issues" (AI's). For the text of these AI's, see www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs. Included with GNAT releases is a file `features-ada0y' that describes the current set of implemented Ada 2005 features.

If these features are used in Ada 95 mode (which is the normal default), then error messages or warnings may be generated, reflecting the fact that these new features are otherwise unauthorized extensions to Ada 95. The use of the `-gnat05' switch (or an equivalent pragma) causes these messages to be suppressed.

Note that some specialized releases of GNAT (notably the GAP academic version) have Ada 2005 mode on by default, and in such environments, the Ada 2005 features can be used freely without the use of switches.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.11 Character Set Control

`-gnatic'

Normally GNAT recognizes the Latin-1 character set in source program identifiers, as described in the Ada 95 Reference Manual. This switch causes GNAT to recognize alternate character sets in identifiers. c is a single character indicating the character set, as follows:

1
ISO 8859-1 (Latin-1) identifiers

2
ISO 8859-2 (Latin-2) letters allowed in identifiers

3
ISO 8859-3 (Latin-3) letters allowed in identifiers

4
ISO 8859-4 (Latin-4) letters allowed in identifiers

5
ISO 8859-5 (Cyrillic) letters allowed in identifiers

9
ISO 8859-15 (Latin-9) letters allowed in identifiers

p
IBM PC letters (code page 437) allowed in identifiers

8
IBM PC letters (code page 850) allowed in identifiers

f
Full upper-half codes allowed in identifiers

n
No upper-half codes allowed in identifiers

w
Wide-character codes (that is, codes greater than 255) allowed in identifiers

See section 2.2 Foreign Language Representation, for full details on the implementation of these character sets.

`-gnatWe'
Specify the method of encoding for wide characters. e is one of the following:

h
Hex encoding (brackets coding also recognized)

u
Upper half encoding (brackets encoding also recognized)

s
Shift/JIS encoding (brackets encoding also recognized)

e
EUC encoding (brackets encoding also recognized)

8
UTF-8 encoding (brackets encoding also recognized)

b
Brackets encoding only (default value)
For full details on the these encoding methods see 2.2.3 Wide Character Encodings. Note that brackets coding is always accepted, even if one of the other options is specified, so for example `-gnatW8' specifies that both brackets and UTF-8 encodings will be recognized. The units that are with'ed directly or indirectly will be scanned using the specified representation scheme, and so if one of the non-brackets scheme is used, it must be used consistently throughout the program. However, since brackets encoding is always recognized, it may be conveniently used in standard libraries, allowing these libraries to be used with any of the available coding schemes. scheme. If no `-gnatW?' parameter is present, then the default representation is Brackets encoding only.

Note that the wide character representation that is specified (explicitly or by default) for the main program also acts as the default encoding used for Wide_Text_IO files if not specifically overridden by a WCEM form parameter.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.12 File Naming Control

`-gnatkn'
Activates file name "krunching". n, a decimal integer in the range 1-999, indicates the maximum allowable length of a file name (not including the `.ads' or `.adb' extension). The default is not to enable file name krunching.

For the source file naming rules, See section 2.3 File Naming Rules.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.13 Subprogram Inlining Control

`-gnatn'
The n here is intended to suggest the first syllable of the word "inline". GNAT recognizes and processes Inline pragmas. However, for the inlining to actually occur, optimization must be enabled. To enable inlining of subprograms specified by pragma Inline, you must also specify this switch. In the absence of this switch, GNAT does not attempt inlining and does not need to access the bodies of subprograms for which pragma Inline is specified if they are not in the current unit.

If you specify this switch the compiler will access these bodies, creating an extra source dependency for the resulting object file, and where possible, the call will be inlined. For further details on when inlining is possible see 7.1.5 Inlining of Subprograms.

`-gnatN'
The front end inlining activated by this switch is generally more extensive, and quite often more effective than the standard `-gnatn' inlining mode. It will also generate additional dependencies. Note that `-gnatN' automatically implies `-gnatn' so it is not necessary to specify both options.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.14 Auxiliary Output Control

`-gnatt'
Causes GNAT to write the internal tree for a unit to a file (with the extension `.adt'. This not normally required, but is used by separate analysis tools. Typically these tools do the necessary compilations automatically, so you should not have to specify this switch in normal operation.

`-gnatu'
Print a list of units required by this compilation on `stdout'. The listing includes all units on which the unit being compiled depends either directly or indirectly.

`-pass-exit-codes'
If this switch is not used, the exit code returned by gcc when compiling multiple files indicates whether all source files have been successfully used to generate object files or not.

When `-pass-exit-codes' is used, gcc exits with an extended exit status and allows an integrated development environment to better react to a compilation failure. Those exit status are:

5
There was an error in at least one source file.
3
At least one source file did not generate an object file.
2
The compiler died unexpectedly (internal error for example).
0
An object file has been generated for every source file.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.15 Debugging Control

`-gnatdx'
Activate internal debugging switches. x is a letter or digit, or string of letters or digits, which specifies the type of debugging outputs desired. Normally these are used only for internal development or system debugging purposes. You can find full documentation for these switches in the body of the Debug unit in the compiler source file `debug.adb'.

`-gnatG'
This switch causes the compiler to generate auxiliary output containing a pseudo-source listing of the generated expanded code. Like most Ada compilers, GNAT works by first transforming the high level Ada code into lower level constructs. For example, tasking operations are transformed into calls to the tasking run-time routines. A unique capability of GNAT is to list this expanded code in a form very close to normal Ada source. This is very useful in understanding the implications of various Ada usage on the efficiency of the generated code. There are many cases in Ada (e.g. the use of controlled types), where simple Ada statements can generate a lot of run-time code. By using `-gnatG' you can identify these cases, and consider whether it may be desirable to modify the coding approach to improve efficiency.

The format of the output is very similar to standard Ada source, and is easily understood by an Ada programmer. The following special syntactic additions correspond to low level features used in the generated code that do not have any exact analogies in pure Ada source form. The following is a partial list of these special constructions. See the specification of package Sprint in file `sprint.ads' for a full list.

new xxx [storage_pool = yyy]
Shows the storage pool being used for an allocator.

at end procedure-name;
Shows the finalization (cleanup) procedure for a scope.

(if expr then expr else expr)
Conditional expression equivalent to the x?y:z construction in C.

target^(source)
A conversion with floating-point truncation instead of rounding.

target?(source)
A conversion that bypasses normal Ada semantic checking. In particular enumeration types and fixed-point types are treated simply as integers.

target?^(source)
Combines the above two cases.

x #/ y
x #mod y
x #* y
x #rem y
A division or multiplication of fixed-point values which are treated as integers without any kind of scaling.

free expr [storage_pool = xxx]
Shows the storage pool associated with a free statement.

freeze typename [actions]
Shows the point at which typename is frozen, with possible associated actions to be performed at the freeze point.

reference itype
Reference (and hence definition) to internal type itype.

function-name! (arg, arg, arg)
Intrinsic function call.

labelname : label
Declaration of label labelname.

expr && expr && expr ... && expr
A multiple concatenation (same effect as expr & expr & expr, but handled more efficiently).

[constraint_error]
Raise the Constraint_Error exception.

expression'reference
A pointer to the result of evaluating expression.

target-type!(source-expression)
An unchecked conversion of source-expression to target-type.

[numerator/denominator]
Used to represent internal real literals (that) have no exact representation in base 2-16 (for example, the result of compile time evaluation of the expression 1.0/27.0).

`-gnatD'
When used in conjunction with `-gnatG', this switch causes the expanded source, as described above for `-gnatG' to be written to files with names `xxx.dg', where `xxx' is the normal file name, instead of to the standard ooutput file. For example, if the source file name is `hello.adb', then a file `hello.adb.dg' will be written. The debugging information generated by the gcc `-g' switch will refer to the generated `xxx.dg' file. This allows you to do source level debugging using the generated code which is sometimes useful for complex code, for example to find out exactly which part of a complex construction raised an exception. This switch also suppress generation of cross-reference information (see `-gnatx') since otherwise the cross-reference information would refer to the `.dg' file, which would cause confusion since this is not the original source file.

Note that `-gnatD' actually implies `-gnatG' automatically, so it is not necessary to give both options. In other words `-gnatD' is equivalent to `-gnatDG').

`-gnatR[0|1|2|3[s]]'
This switch controls output from the compiler of a listing showing representation information for declared types and objects. For `-gnatR0', no information is output (equivalent to omitting the `-gnatR' switch). For `-gnatR1' (which is the default, so `-gnatR' with no parameter has the same effect), size and alignment information is listed for declared array and record types. For `-gnatR2', size and alignment information is listed for all expression information for values that are computed at run time for variant records. These symbolic expressions have a mostly obvious format with #n being used to represent the value of the n'th discriminant. See source files `repinfo.ads/adb' in the GNAT sources for full details on the format of `-gnatR3' output. If the switch is followed by an s (e.g. `-gnatR2s'), then the output is to a file with the name `file.rep' where file is the name of the corresponding source file.

`-gnatS'
The use of the switch `-gnatS' for an Ada compilation will cause the compiler to output a representation of package Standard in a form very close to standard Ada. It is not quite possible to do this entirely in standard Ada (since new numeric base types cannot be created in standard Ada), but the output is easily readable to any Ada programmer, and is useful to determine the characteristics of target dependent types in package Standard.

`-gnatx'
Normally the compiler generates full cross-referencing information in the `ALI' file. This information is used by a number of tools, including gnatfind and gnatxref. The `-gnatx' switch suppresses this information. This saves some space and may slightly speed up compilation, but means that these tools cannot be used.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.16 Exception Handling Control

GNAT uses two methods for handling exceptions at run-time. The setjmp/longjmp method saves the context when entering a frame with an exception handler. Then when an exception is raised, the context can be restored immediately, without the need for tracing stack frames. This method provides very fast exception propagation, but introduces significant overhead for the use of exception handlers, even if no exception is raised.

The other approach is called "zero cost" exception handling. With this method, the compiler builds static tables to describe the exception ranges. No dynamic code is required when entering a frame containing an exception handler. When an exception is raised, the tables are used to control a back trace of the subprogram invocation stack to locate the required exception handler. This method has considerably poorer performance for the propagation of exceptions, but there is no overhead for exception handlers if no exception is raised. Note that in this mode and in the context of mixed Ada and C/C++ programming, to propagate an exception through a C/C++ code, the C/C++ code must be compiled with the `-funwind-tables' GCC's option.

The following switches can be used to control which of the two exception handling methods is used.

`--RTS=sjlj'
This switch causes the setjmp/longjmp run-time to be used for exception handling. If this is the default mechanism for the target (see below), then this has no effect. If the default mechanism for the target is zero cost exceptions, then this switch can be used to modify this default, and must be used for all units in the partition. This option is rarely used. One case in which it may be advantageous is if you have an application where exception raising is common and the overall performance of the application is improved by favoring exception propagation.

`--RTS=zcx'
This switch causes the zero cost approach to be used for exception handling. If this is the default mechanism for the target (see below), then this has no effect. If the default mechanism for the target is setjmp/longjmp exceptions, then this switch can be used to modify this default, and must be used for all units in the partition. This option can only be used if the zero cost approach is available for the target in use (see below).

The setjmp/longjmp approach is available on all targets, while the zero cost approach is available on selected targets. To determine whether zero cost exceptions can be used for a particular target, look at the private part of the file system.ads. Either GCC_ZCX_Support or Front_End_ZCX_Support must be True to use the zero cost approach. If both of these switches are set to False, this means that zero cost exception handling is not yet available for that target. The switch ZCX_By_Default indicates the default approach. If this switch is set to True, then the zero cost approach is used by default.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.17 Units to Sources Mapping Files

`-gnatempath'
A mapping file is a way to communicate to the compiler two mappings: from unit names to file names (without any directory information) and from file names to path names (with full directory information). These mappings are used by the compiler to short-circuit the path search.

The use of mapping files is not required for correct operation of the compiler, but mapping files can improve efficiency, particularly when sources are read over a slow network connection. In normal operation, you need not be concerned with the format or use of mapping files, and the `-gnatem' switch is not a switch that you would use explicitly. it is intended only for use by automatic tools such as gnatmake running under the project file facility. The description here of the format of mapping files is provided for completeness and for possible use by other tools.

A mapping file is a sequence of sets of three lines. In each set, the first line is the unit name, in lower case, with "%s" appended for specifications and "%b" appended for bodies; the second line is the file name; and the third line is the path name.

Example:
 
   main%b
   main.2.ada
   /gnat/project1/sources/main.2.ada

When the switch `-gnatem' is specified, the compiler will create in memory the two mappings from the specified file. If there is any problem (non existent file, truncated file or duplicate entries), no mapping will be created.

Several `-gnatem' switches may be specified; however, only the last one on the command line will be taken into account.

When using a project file, gnatmake create a temporary mapping file and communicates it to the compiler using this switch.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.18 Integrated Preprocessing

GNAT sources may be preprocessed immediately before compilation; the actual text of the source is not the text of the source file, but is derived from it through a process called preprocessing. Integrated preprocessing is specified through switches `-gnatep' and/or `-gnateD'. `-gnatep' indicates, through a text file, the preprocessing data to be used. `-gnateD' specifies or modifies the values of preprocessing symbol.

It is recommended that gnatmake switch -s should be used when Integrated Preprocessing is used. The reason is that preprocessing with another Preprocessing Data file without changing the sources will not trigger recompilation without this switch.

Note that gnatmake switch -m will almost always trigger recompilation for sources that are preprocessed, because gnatmake cannot compute the checksum of the source after preprocessing.

The actual preprocessing function is described in details in section 16. Preprocessing Using gnatprep. This section only describes how integrated preprocessing is triggered and parameterized.

-gnatep=file
This switch indicates to the compiler the file name (without directory information) of the preprocessor data file to use. The preprocessor data file should be found in the source directories.

A preprocessing data file is a text file with significant lines indicating how should be preprocessed either a specific source or all sources not mentioned in other lines. A significant line is a non empty, non comment line. Comments are similar to Ada comments.

Each significant line starts with either a literal string or the character '*'. A literal string is the file name (without directory information) of the source to preprocess. A character '*' indicates the preprocessing for all the sources that are not specified explicitly on other lines (order of the lines is not significant). It is an error to have two lines with the same file name or two lines starting with the character '*'.

After the file name or the character '*', another optional literal string indicating the file name of the definition file to be used for preprocessing (see section 16.3 Form of Definitions File). The definition files are found by the compiler in one of the source directories. In some cases, when compiling a source in a directory other than the current directory, if the definition file is in the current directory, it may be necessary to add the current directory as a source directory through switch -I., otherwise the compiler would not find the definition file.

Then, optionally, switches similar to those of gnatprep may be found. Those switches are:

-b
Causes both preprocessor lines and the lines deleted by preprocessing to be replaced by blank lines, preserving the line number. This switch is always implied; however, if specified after `-c' it cancels the effect of `-c'.

-c
Causes both preprocessor lines and the lines deleted by preprocessing to be retained as comments marked with the special string "--! ".

-Dsymbol=value
Define or redefine a symbol, associated with value. A symbol is an Ada identifier, or an Ada reserved word, with the exception of if, else, elsif, end, and, or and then. value is either a literal string, an Ada identifier or any Ada reserved word. A symbol declared with this switch replaces a symbol with the same name defined in a definition file.

-s
Causes a sorted list of symbol names and values to be listed on the standard output file.

-u
Causes undefined symbols to be treated as having the value FALSE in the context of a preprocessor test. In the absence of this option, an undefined symbol in a #if or #elsif test will be treated as an error.

Examples of valid lines in a preprocessor data file:

 
  "toto.adb"  "prep.def" -u
  --  preprocess "toto.adb", using definition file "prep.def",
  --  undefined symbol are False.

  * -c -DVERSION=V101
  --  preprocess all other sources without a definition file;
  --  suppressed lined are commented; symbol VERSION has the value V101.

  "titi.adb" "prep2.def" -s
  --  preprocess "titi.adb", using definition file "prep2.def";
  --  list all symbols with their values.

-gnateDsymbol[=value]
Define or redefine a preprocessing symbol, associated with value. If no value is given on the command line, then the value of the symbol is True. A symbol is an identifier, following normal Ada (case-insensitive) rules for its syntax, and value is any sequence (including an empty sequence) of characters from the set (letters, digits, period, underline). Ada reserved words may be used as symbols, with the exceptions of if, else, elsif, end, and, or and then.

A symbol declared with this switch on the command line replaces a symbol with the same name either in a definition file or specified with a switch -D in the preprocessor data file.

This switch is similar to switch `-D' of gnatprep.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.2.19 Code Generation Control

The GCC technology provides a wide range of target dependent `-m' switches for controlling details of code generation with respect to different versions of architectures. This includes variations in instruction sets (e.g. different members of the power pc family), and different requirements for optimal arrangement of instructions (e.g. different members of the x86 family). The list of available `-m' switches may be found in the GCC documentation.

Use of the these `-m' switches may in some cases result in improved code performance.

The GNAT Pro technology is tested and qualified without any `-m' switches, so generally the most reliable approach is to avoid the use of these switches. However, we generally expect most of these switches to work successfully with GNAT Pro, and many customers have reported successful use of these options.

Our general advice is to avoid the use of `-m' switches unless special needs lead to requirements in this area. In particular, there is no point in using `-m' switches to improve performance unless you actually see a performance improvement.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.3 Search Paths and the Run-Time Library (RTL)

With the GNAT source-based library system, the compiler must be able to find source files for units that are needed by the unit being compiled. Search paths are used to guide this process.

The compiler compiles one source file whose name must be given explicitly on the command line. In other words, no searching is done for this file. To find all other source files that are needed (the most common being the specs of units), the compiler examines the following directories, in the following order:

  1. The directory containing the source file of the main unit being compiled (the file name on the command line).

  2. Each directory named by an `-I' switch given on the gcc command line, in the order given.

  3. Each of the directories listed in the text file whose name is given by the ADA_PRJ_INCLUDE_FILE environment variable.

    ADA_PRJ_INCLUDE_FILE is normally set by gnatmake or by the gnat driver when project files are used. It should not normally be set by other means.

  4. Each of the directories listed in the value of the ADA_INCLUDE_PATH environment variable. Construct this value exactly as the PATH environment variable: a list of directory names separated by colons (semicolons when working with the NT version).

  5. The content of the `ada_source_path' file which is part of the GNAT installation tree and is used to store standard libraries such as the GNAT Run Time Library (RTL) source files. 19.2.2 Installing a library

Specifying the switch `-I-' inhibits the use of the directory containing the source file named in the command line. You can still have this directory on your search path, but in this case it must be explicitly requested with a `-I' switch.

Specifying the switch `-nostdinc' inhibits the search of the default location for the GNAT Run Time Library (RTL) source files.

The compiler outputs its object files and ALI files in the current working directory. Caution: The object file can be redirected with the `-o' switch; however, gcc and gnat1 have not been coordinated on this so the `ALI' file will not go to the right place. Therefore, you should avoid using the `-o' switch.

The packages Ada, System, and Interfaces and their children make up the GNAT RTL, together with the simple System.IO package used in the "Hello World" example. The sources for these units are needed by the compiler and are kept together in one directory. Not all of the bodies are needed, but all of the sources are kept together anyway. In a normal installation, you need not specify these directory names when compiling or binding. Either the environment variables or the built-in defaults cause these files to be found.

In addition to the language-defined hierarchies (System, Ada and Interfaces), the GNAT distribution provides a fourth hierarchy, consisting of child units of GNAT. This is a collection of generally useful types, subprograms, etc. See the GNAT Reference Manual for further details.

Besides simplifying access to the RTL, a major use of search paths is in compiling sources from multiple directories. This can make development environments much more flexible.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.4 Order of Compilation Issues

If, in our earlier example, there was a spec for the hello procedure, it would be contained in the file `hello.ads'; yet this file would not have to be explicitly compiled. This is the result of the model we chose to implement library management. Some of the consequences of this model are as follows:


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

3.5 Examples

The following are some typical Ada compilation command line examples:

$ gcc -c xyz.adb
Compile body in file `xyz.adb' with all default options.

$ gcc -c -O2 -gnata xyz-def.adb

Compile the child unit package in file `xyz-def.adb' with extensive optimizations, and pragma Assert/Debug statements enabled.

$ gcc -c -gnatc abc-def.adb
Compile the subunit in file `abc-def.adb' in semantic-checking-only mode.


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by Mail Server on June, 15 2005 using texi2html