I am a beginner for c++ i was going through some code where i read that global variables persist till the end of our program and static global variables will have scope till the end of that file.Here is an example program where am trying to access both global and static global variables in another file.
Could anyone please explain how is it possible to use extern for static global variable in c++?
If i have a header file with both global and static global variables and i include it in my source file ans use extern for both and print values its printing
If i do so it wont give any error or warning. program will run and both values are displayed in source file
Header file header.h
int varGlobal;
static int staticVarGlobal = 10
Source file
#include<iostream>
#include "header.h"
extern int varGlobal;
extern int staticVarGlobal;
using namespace std;
int main()
{
cout<<"Global variable : "<<varGlobal<<endl;
cout<<"Static Global variable : "<<++staticVarGlobal<<endl;
}
Output
Global variable : 0
Static Global variable : 11
So how does this work?