c++ - global variable doesn't work -


i have global int want change in different files, reason doesn't work.

i have:

//test.h

 #include <windows.h>  static int start1; //want use 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 go something() start1 0, instead of 3? have been trying make global variable hours, , doesn't work. please can clarify?

don't declare static variable in header file. result in separate variable existing each translation unit (i.e. source file) includes header file.

the canonical pattern declare variable extern in header file, , define "normally" in 1 source file.


Comments