| re: Strange problem about static data
Russoue wrote:[color=blue]
> I am having a strange problem. I have a static int with an initial
> value in a header file which I include from two source files. In one
> file, I assign a value to that int but the other file don't get it. I
> have printed the value from both files. The first line printed from the
> first file shows the assigned value but the second line printed from
> the second file shows the initial value. How can this happen?
>
> Here is an example:
>
> File: Header.h
> ==============
>
> #ifndef _HEADER_H_
> #define _HEADER_H_
> static int g_iVerboseLevel = 6;
> #endif
>
> File: Header2.h
> ===============
> #ifndef _HEADER2_H_
> #define _HEADER2_H_
>
> void ChangeValue();
>
> #endif
>
> File: File2.cpp
> ===============
> #include <iostream>
> #include "Header.h"[/color]
After you include this file.
There is g_iVerboseLevel which is can be seen only this file due to
keyword 'static' and this var has initialised as 6.
So, File2.o will have this var inside.
[color=blue]
>
> using namespace std;
> void ChangeValue()
> {
> std::cout << "Value from ChangeValue is " << g_iVerboseLevel <<
> '\n';[/color]
You've print out g_iVerboseLevel which is inside File2.o (val = 6).
[color=blue]
> }
>
> File: File1.cpp
> ===============
> #include "Header.h"[/color]
You've included this header file.
So, you have g_iVerboseLevel for File1.o, and can be seen only this
file.
[color=blue]
> #include <iostream>
> #include "Header2.h"[/color]
include ChangeValue(); for use below.[color=blue]
>
> using namespace std;
>
> int main(void)
> {
> g_iVerboseLevel = 4;[/color]
Assign g_iVerboseLevel(inside File1.o)
[color=blue]
> std::cout << "Value of g_iVerboseLevel from main is " <<
> g_iVerboseLevel << '\n';[/color]
Print out g_iVerboseLevel(inside File1.o which is 4)
[color=blue]
> ChangeValue();[/color]
Print out g_iVerboseLevel(inside File2.o which is 6)
[color=blue]
> std::cout << "Value of g_iVerboseLevel from main is " <<
> g_iVerboseLevel << endl;[/color]
Print out g_iVerboseLevel(inside File1.o again).[color=blue]
> return 0;
> }
>
>
>
> The output:
> Value of g_iVerboseLevel from main is 4
> Value from ChangeValue is 6
> Value of g_iVerboseLevel from main is 4
>
> Can anybody explain?[/color]
conclusion:
You have 2 g_iVerboseLevel in your executable program.
Regards, |