Next: , Previous: Debugging - A Special Case, Up: Conditional Compilation


D.3 Conditionalizing Declarations

In some cases, it may be necessary to conditionalize declarations to meet different requirements. For example we might want a bit string whose length is set to meet some hardware message requirement.

In some cases, it may be possible to do this using declare blocks controlled by conditional constants:

     if Small_Machine then
        declare
           X : Bit_String (1 .. 10);
        begin
           ...
        end;
     else
        declare
           X : Large_Bit_String (1 .. 1000);
        begin
           ...
        end;
     end if;

Note that in this approach, both declarations are analyzed by the compiler so this can only be used where both declarations are legal, even though one of them will not be used.

Another approach is to define integer constants, e.g. Bits_Per_Word, or Boolean constants, e.g. Little_Endian, and then write declarations that are parameterized by these constants. For example

     for Rec use
       Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
     end record;

If Bits_Per_Word is set to 32, this generates either

     for Rec use
       Field1 at 0 range 0 .. 32;
     end record;

for the big endian case, or

     for Rec use record
       Field1 at 0 range 10 .. 32;
     end record;

for the little endian case. Since a powerful subset of Ada expression notation is usable for creating static constants, clever use of this feature can often solve quite difficult problems in conditionalizing compilation (note incidentally that in Ada 95, the little endian constant was introduced as System.Default_Bit_Order, so you do not need to define this one yourself).