[LC++]declaring and using manipulating global variables

Paul Gearon pag at PISoftware.com
Fri May 16 11:01:02 UTC 2003


On Fri, 16 May 2003, Julien Patrick Claassen wrote:

> I simply tried it with something like:
>
> #include <something>
> int glob_index;
> (functions here using glob_index);
> int main()
> {
>   glob_index = 6;
>   change_glob_index(); // being a function that manipulates glob_index
>   return 0;
> }
>
>   I used some simple output to see the value of glob_index and saw, that it is
> only changed locally.
>   Is there a - let's say - more elegant way of doing this? Or is my way the
> usual?

This looks correct, but pseudocode can be misleading.  The following works
just fine...

/////////// BEGIN CODE //////////////////
#include <stdio.h>

int glob_index;

void change_glob_index() {
  glob_index += 4;
}

int main() {
  glob_index = 6;
  printf("Initial value of glob_index = %d\n", glob_index);
  change_glob_index();
  printf("Final value of glob_index = %d\n", glob_index);
  return 0;
}
/////////// END CODE //////////////////

The most obvious error to cause multiple local instances of a global
variable is to declare it in a header file and include it in several
source files.  This results in numerous object files allocating space for
the variable, and each one refers to its own local instance.

Only one source file should end up declaring:
  int glob_index;
As this allocates the memory for the variable.  All the other source files
need to declare:
  extern int glob_index;
As this declares that the variable exists, but does not allocate storage
for it.  Instead it tells the linker to find another object file which
does the allocation.

Regards,
Paul Gearon

Software Engineer                Telephone:   +61 7 3876 2188
Plugged In Software              Fax:         +61 7 3876 4899
http://www.PIsoftware.com        PGP Key available via finger

Catapultam habeo. Nisi pecuniam omnem mihi dabis, ad caput tuum saxum
immane mittam.
(Translation from latin: "I have a catapult. Give me all the money,
or I will fling an enormous rock at your head.")





More information about the tuxCPProgramming mailing list