Next: , Previous: Common Sources with Different Switches and Directories, Up: Examples of Project Files


11.2.2 Using External Variables

Instead of supplying different project files for debug and release, we can define a single project file that queries an external variable (set either on the command line or via an environment variable) in order to conditionally define the appropriate settings. Again, assume that the source files pack.ads, pack.adb, and proc.adb are located in directory /common. The following project file, build.gpr, queries the external variable named STYLE and defines an object directory and switch settings based on whether the value is "deb" (debug) or "rel" (release), and where the default is "deb".

     project Build is
       for Main use ("proc");
     
       type Style_Type is ("deb", "rel");
       Style : Style_Type := external ("STYLE", "deb");
     
       case Style is
         when "deb" =>
           for Object_Dir use "debug";
     
         when "rel" =>
           for Object_Dir use "release";
           for Exec_Dir use ".";
       end case;
     
       package Builder is
     
         case Style is
           when "deb" =>
             for Default_Switches ("Ada")
                 use ("-g");
             for Executable ("proc") use "proc1";
           when others =>
             null;
         end case;
     
       end Builder;
     
       package Compiler is
     
         case Style is
           when "deb" =>
             for Default_Switches ("Ada")
                 use ("-gnata",
                      "-gnato",
                      "-gnatE");
     
           when "rel" =>
             for Default_Switches ("Ada")
                 use ("-O2");
         end case;
     
       end Compiler;
     
     end Build;

Style_Type is an example of a string type, which is the project file analog of an Ada enumeration type but whose components are string literals rather than identifiers. Style is declared as a variable of this type.

The form external("STYLE", "deb") is known as an external reference; its first argument is the name of an external variable, and the second argument is a default value to be used if the external variable doesn't exist. You can define an external variable on the command line via the -X switch, or you can use an environment variable as an external variable.

Each case construct is expanded by the Project Manager based on the value of Style. Thus the command

     gnatmake -P/common/build.gpr -XSTYLE=deb

is equivalent to the gnatmake invocation using the project file debug.gpr in the earlier example. So is the command

     gnatmake -P/common/build.gpr

since "deb" is the default for STYLE.

Analogously,

     gnatmake -P/common/build.gpr -XSTYLE=rel

is equivalent to the gnatmake invocation using the project file release.gpr in the earlier example.