I have a global int I want to change in different files, for some reason it doesn’t work.
I have:
//test.h
#include <windows.h>
static int start1; //want to use this globally.
//declare
void something();
//test.cpp
#include "test.h"
extern int start1;
void something()
{
start1 = start1 + 1;
}
//main.cpp
#include "test.h"
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
start1 = 3;
something();
return 0;
}
Why, when you go into something() is start1 0, instead of 3? I have been trying to make a global variable for hours, and it doesn’t work. Please can someone clarify?
Don’t declare a
staticvariable in a header file. That will result in a separate variable existing for each translation unit (i.e. source file) that includes that header file.The canonical pattern is to declare the variable as
externin the header file, and then define it “normally” in one source file.