1

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!

anurag86
  • 209
  • 1
  • 3
  • 9

1 Answers1

2

This is because you included h1.h in s1.cpp, so (concerning your question) you have something like:

extern const int a;
const int a = 9;

Which means that a is declared to have external linkage and is then defined and initialized here, so a is thus visible in the other module s2.cpp which only includes h1.h:

extern const int a;
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • 1
    Well then in which scenario do you think will make me prepend the keyword extern without which it will throw the error? – anurag86 Feb 11 '17 at 12:00