0

Possible Duplicate:
const and global

This code will produce error in c++

// Foo.cpp
const int Foo = 99;

// Main.cpp
extern const int Foo;
int main()
{
    cout << Foo << endl;
    return 0;
}    

Reason as given by many is global const has internal scope and it is default static.

solution to this is :-

    //Foo.h
    extern const int Foo; 

    // Foo.cpp
    #include "Foo.h"
    const int Foo = 99; 

    // Main.cpp
    #include "Foo.h"
    int main()
    {
       cout << Foo << endl;
    }

I used to think that extern is used to tell compiler that memory for the indentifer is already allocated somewhere in other files.
Applying same logic on above code can anyone explain what is happening here or extern has different meaning in c++??
enter link description here
Also consider this page it is spoiling my all intuitions..

Community
  • 1
  • 1
T.J.
  • 1,466
  • 3
  • 19
  • 35
  • 1
    Didn't you ask the same Question about 2 hrs ago? Have you read the answers there? If you still had doubts about the Q you asked previously you should add your doubts as comments to the answers,not start a new question for it. – Alok Save Jan 27 '12 at 13:54
  • @als i think to clear doubts of others is best thing to do at SO. – T.J. Jan 27 '12 at 15:02
  • Well, not by asking the same question again and again,If you don't understand an answer, ask doubts in the comments section under the answer,not start another question.Please read the SO FAQ. – Alok Save Jan 27 '12 at 15:11

1 Answers1

0

Added an extern ... line to the CPP, which - I think - kills the internal linkage behavior of the next line.

// Foo.cpp
extern const int Foo;
const int Foo = 99;

Also made some unrelated corrections to Main:

// Main.cpp
#include <iostream>
extern const int Foo;
int main()
{
    using namespace std;
    cout << Foo << endl;
    return 0;
}

They are #include <iostream> and using namespace std;.

This answer is not carefully reasoned theoretically, but works for me with g++.

Notinlist
  • 16,144
  • 10
  • 57
  • 99
  • UPDATE: If you write `const int Foo = 99` into Foo.cpp, that's also correct. The post referenced by Als explains. – Notinlist Jan 27 '12 at 14:07