Tony The Lion
Tony The Lion

Reputation: 63200

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?

Upvotes: 0

Views: 1564

Answers (3)

user1712937
user1712937

Reputation:

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.

Upvotes: 0

spencercw
spencercw

Reputation: 3358

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.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

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.

Upvotes: 11

Related Questions