UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

14.5.  Defining symbols

The print_line function prints a line with the - symbol repeated as many times as indicated by its only parameter. This value is passed from the line_width variable declared and assigned in the first line of the main function. If the program had to be executed in devices with screen width of 20, 40 and 60 characters, How would you obtain these three versions? In other words, you have to obtain three executables of the same program, but they have to print lines of different length.

The compiler offers a functionality that is very useful in these cases. Edit the program and delete the first line in the main function where the variable line_width is declared and assigned a value. Modify the two lines that call the print_line function such that they read:

print_line(LINEWIDTH);

The program is apparently incorrect because there is a symbol, namely LINEWIDTH which is used but not declared anywhere. Compile the program but using the -D option followed by the definition LINEWIDTH=80 as it is shown in the following command:

$ gcc -DLINEWIDTH=80 -o main_en main_en.c

As you can see, the compiler does not inform of any error and the executable is created normally. The -D option followed by a symbol name and (optionally) an equal sign and a value makes the compiler to pre-process the source code and replace all appearances of the symbol by the given value. Careful, the compiler is performing a textual replacement, in other words, the program has no symbol with name LINEWIDTH but in the program there are two lines than in the previous compilation were processed as

print_line(80)

Try to re-compile with different values for the LINEWIDTH symbol and check that the lines are printed with different lengths. What happens if you omit in the compile command the equal sign and the value? To distinguish in the code those symbols in the program from those that are processed with this textual replacement, the policy (not mandatory) is to write them all in capital letters.