Next: , Previous: Executable File Names, Up: Building With Projects


11.2.7 Avoid Duplication With Variables

To illustrate some other project capabilities, here is a slightly more complex project using similar sources and a main program in C:

     project C_Main is
        for Languages    use ("Ada", "C");
        for Source_Dirs  use ("common");
        for Object_Dir   use  "obj";
        for Main         use ("main.c");
        package Compiler is
           C_Switches := ("-pedantic");
           for Default_Switches ("C")   use C_Switches;
           for Default_Switches ("Ada") use ("-gnaty");
           for Switches ("main.c") use C_Switches & ("-g");
        end Compiler;
     end C_Main;

This project has many similarities with the previous one. As expected, its Main attribute now refers to a C source. The attribute Exec_Dir is now omitted, thus the resulting executable will be put in the directory obj.

The most noticeable difference is the use of a variable in the Compiler package to store settings used in several attributes. This avoids text duplication, and eases maintenance (a single place to modify if we want to add new switches for C files). We will revisit the use of variables in the context of scenarios (see Scenarios in Projects).

In this example, we see how the file main.c can be compiled with the switches used for all the other C files, plus -g. In this specific situation the use of a variable could have been replaced by a reference to the Default_Switches attribute:

        for Switches ("c_main.c") use Compiler'Default_Switches ("C") & ("-g");

Note the tick (') used to refer to attributes defined in a package.

Here is the output of the GPRbuild command using this project:

     $gprbuild -Pc_main
     gcc -c -pedantic -g main.c
     gcc -c -gnaty proc.adb
     gcc -c -gnaty pack.adb
     gcc -c -pedantic utils.c
     gprbind main.bexch
     ...
     gcc main.o -o main

The default switches for Ada sources, the default switches for C sources (in the compilation of lib.c), and the specific switches for main.c have all been taken into account.