A commonly used C preprocessor trick to handle
definition and declaration of global variables
How to organize the global variables in a
multi-files C program
The global variables in a
multi-filesC program are
organized as
follows:
Eachglobal variable
must be defined inside
exactly one of the files
Eachglobal variable
must be declared inside
every C program files
A simple way to achieve this is:
Defineeach global variable inside
one of the C program files
Declareeach global variable inside
every C program files
(except in the one in which they have been defined)
Schematically:
In order to understandhow to
organize the
definitions and declarations
of the global variables in a
C program
with ease, we must
first learn about a
new feature of the
C pre-processor.
Recall: conditional compilation feature in the C pre-processor
Conditional clause of
the C pre-processor:
The C pre-processor has a
conditional clause that
tells the C processor whether it should
skip the
processing
of a portion of the C program file
The C pre-processor has the following
3 conditional clauses:
#if
#ifdef
#ifndef
#ifndef:
The #ifndefconditional is similar to
the #ifdef, except
the meaning is
reversed:
#ifndef MACRO-NAME
text segment
#endif
the text segment is
kept (= included) when the
macro name MACR-NAME
is not defined
The text segment is
omittedotherwise
(when the
macro name MACR-NAME
is defined)
A programming trick to manage
definitions/declarations of global variables
used in multiple C program files
Recal, we
want make it
easy to
achieve this simple way to
organize
definitions/declarations
of global variables:
Defineeach global variable inside
one of the C program files
Declareeach global variable inside
every C program files
(except in the one in which they have been defined)
Schematically:
Programming trick:
Create a header file containing
all the global variables
as follows: