global variable doesn't work

2019-01-29 11:06发布

问题:

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?

回答1:

Don't declare a static variable 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 extern in the header file, and then define it "normally" in one source file.



回答2:

You need to declare your int as extern in your header. It doesn't need any qualifiers when you define it in your .cpp file. The static qualifier actually means that the int you are declaring is only accessible in the current translation unit, so each .cpp file will get a different version of it.



回答3:

If you put

static int start1;

in all source files, you'll get a static effect, in that the data will be separate addresses within each. Then you can keep separate values/content for each unit.

BUT. This is NOT a global variable per se. A global variable is one that is shared between units, not the opposite. So there is a difference in static behaviour and global (extern) content... So the above answers are right, but I thought I might add a little perspective to the discussion.

I just ran a similar setup in C, and static variables act the same.