It is said that for const variables to be referred from outside(i.e. to have external linkage), extern
keyword is mandatory. So:
const int f = 3; // Definition of f with internal linkage (due to const)
extern const int g; // Declaration of g with external linkage
If that is correct then how does the following still work fine:
In s1.cpp I have declared and initialized const int a=9
without extern
:
s1.cpp
#include<iostream>
#include"h1.h"
using namespace std;
//This is a global variable
const int a=9; // No Extern here
int main()
{
cout<<a;
something();
return 0;
}
h1.h
#ifndef H1_H
#define H1_H
extern const int a; //this extern is anyways required
void something();
#endif
But here is s2.cpp i can still access a
without any problem.
s2.cpp
#include<iostream>
#include"h1.h"
using namespace std;
void something()
{
cout<<"Inside something its : "<<a; //No problem here. Why?
}
Can someone please clarify?
I ran it on linux gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC)
Compiled as : g++ s1.cpp s2.cpp -o out
Output as : 9Inside something its : 9indlin1738!