Q:

c++ Update static int

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

A:

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;
}

A:

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;
}

