UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

14.11.2.  The #define directive

The #define directive has two versions. If the directive is followed by only one string as in the example

#define MAEMO_SYSTEM

the preprocessor simply annotates internally that the symbol is defined. In Section 14.11.3 a directive is described that can check for those symbols that are defined.

The second version of this directive is when it is followed by two strings. In this case, from this point on, the preprocessor replaces all appearances of the first string by the second. The following example defines the symbol MAXIMUM_LOAD to be replaced by the value 1500.

#define MAXIMUM_LOAD 1500

The effect of this directive is identical to the use of the -D option in the compiler. In fact, when the compiler is run with the option -Dname=value, this definition is the same as if the preprocessor would find the line #define name value.

With the #define directive you must take into account the following:

  • This directive is usually at the top of the source files, or if needed in several of them, in a file with extension .h that is included in other files.

  • To differentiate in the code the regular symbols in a program from those defined with the #define directive and that will be replaced by their equivalent, the latter are typically written with all capital letters (this is a convention, the preprocessor does not perform any check).

  • Replacing a symbol by its value is done in all the text in a file. This includes the also the preprocessor directives. In the following example

    #define ONE 1
    #define ANOTHER_ONE ONE
    
    int main(argc, char *argv[]) 
    {
        printf("%d\n", ANOTHER_ONE);
    }

    the program prints the number one. This means that the second #define directive is processes as #define ANOTHER_ONE 1 after replacing ONE by the definition of the previous line.