Home > database >  Identification problem in variables belonging to extern storage class
Identification problem in variables belonging to extern storage class

Time:01-28

a.cpp

extern int var;

int func(){
    return var;
}

main.cpp

#include <iostream>
using namespace std;
  
extern int func();

int main(){
    int var = 12;
    cout << func();
}

When I write as above, I get this error "undefined reference to var".

a.cpp

extern int var;

int func(){
    return var;
}

main.cpp

#include <iostream>
using namespace std;
  
extern int func();
int var = 12;
int main(){
    cout << func();
}

But when I make the above change in the main.cpp file, the application compiles without any problems and 12 is printed on the screen.

Why does this problem occur?

CodePudding user response:

Well, you never know if it's a troll, but in short, your first set of functions declare var as a local variable, within the scope of main() only. As such you may not reference it in a.cpp. Imagine if you did... the lifetime of var is (strictly) temporary (irrespective of being in the "main" function) and is not reserved in RAM, and as such the compiler will not allow the use of extern in a.cpp... what address could it use?

The second time you correctly declare var as a global, within main.cpp. As such your extern in a.cpp is valid, and you can thus reference var. In this case var is reserved in RAM, and accessible from files that declare it extern.

CodePudding user response:

In the first case, the variable is local to function main(). You cannot reference such local variables from other functions. In the second case it is a global variable. That works.

  •  Tags:  
  • Related