Definitions and Macros
As discussed previously, compiler directives are a means of directing the compiler to make decisions or perform actions.
In addition to the include directive seen earlier (refer to the Excursion in the section "The printf Command," on page 91, for an introduction to compiler directives), directives exist for defining constants and macros within a program.
The define Directive
Use the define compiler directive to instruct the compiler to perform a Search and Replace for the item being defined.
For instance, defining a constant GLOBAL in a header file included by multiple files is one method of managing global variables.
100: #ifndef GLOBAL 101: #define GLOBAL 102: #else 103: #define GLOBAL extern 104: #endif 105: GLOBAL int lineno;
Recognizing that variables declared external to extend their scope to multiple files must have an actual definition, the macro GLOBAL is a graceful way to accomplish it.
The first time the compiler sees this code fragment, GLOBAL is not defined, thus the compiler directive ifndef results in true and the compiler defines GLOBALalbeit with an empty value.
101: #define GLOBAL
After you've defined GLOBAL to an initial empty value, line 105 appears as the actual definition for lineno.
105: int lineno;
Subsequent inclusions of this code fragment by other source files result in the test for GLOBAL as not defined (ifndef), resulting in false because GLOBAL was defined with the initial inclusion as the empty value. Therefore, the compiler directive else is performed, setting GLOBAL to extern. This time, when line 105 is reached, the variable lineno is defined as external.
105: extern int lineno;
The actual definition of the variable lineno is effectively in the first source file, which included the header containing this fragment. Subsequent inclusions result in lineno being referenced as an external variable.
More examples of macros and constants are seen in the Graphics Editor project.