简体   繁体   中英

global variable doesn't work

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 static variable in a header file. That will result in a separate variable existing for each translation unit (ie 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM