0

i am trying to update static int

test.h

static int Delay = 0;
void UpdateDelay();

test.cpp

#include "test.h"

void UpdateDelay(){
Delay = 500;
}

Main.cpp

    #include "test.h"

    int main(){
    UpdateDelay();
    std::cout << Delay << std::endl;
    return 0;

}

output should be : 500 but it shows : 0

Thx

beshoy Mounir
  • 95
  • 1
  • 2
  • 11
  • 2
    `static` in this context means internal linkage – each translation unit will get a _different_ `Delay`. – ildjarn Feb 19 '13 at 20:38

4 Answers4

6

A global variable declared as static has internal linkage. This means that each translation unit (i.e. .cpp file) gets a private copy of that variable.

Changes done to a private copy of one translation unit won't have any effect on private copies of the same variable held by different translation units.

If you want to share one global variable, provide one definition for it in a single translation unit, and let all other translation unit refer it through a declaration that specifies the extern keyword:

test.h

extern int Delay;
void UpdateDelay();

test.cpp

#include "test.h"

void UpdateDelay(){
    Delay = 500;
}

main.cpp

#include "test.h"

int Delay = 0; // Do not declare this as static, or you will give
               // internal linkage to this variable. That means it
               // won't be visible from other translation units.

int main(){
    UpdateDelay();
    std::cout << Delay << std::endl;
    return 0;
}
Community
  • 1
  • 1
Andy Prowl
  • 124,023
  • 23
  • 387
  • 451
3

If you put static int Delay in the .h file then each .cpp file will have it's own unique instance.

You want to use extern.

test.h

extern int Delay;
void UpdateDelay();

test.cpp

#include "test.h"
int Delay = 0;

void UpdateDelay()
{
    Delay = 500;
}
David Hope
  • 2,216
  • 16
  • 32
  • You cannot use `static` to define `Delay`, or you will give it internal linkage and it won't be visible within `main.cpp` – Andy Prowl Feb 19 '13 at 20:48
0

you can't declare static int Delay in your .h what happens is per cpp is it makes their own version of "Delay"

what you want to do is in test.cpp declare static int Delay just above your UpdateDelay

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
0

In this usage, the keyword static means that each cpp file has its own independent copy of a variable called Delay. So the one which UpdateDelay() changes is not the one that main() prints.

If you want to use a single variable, make it extern instead: In the header file, put extern int Delay;. In one source file, put int Delay = 0;.

aschepler
  • 70,891
  • 9
  • 107
  • 161