I am trying to learn what "extern" does. I have a simple program where in main's header, a variable is declared with extern. In main, that variable is defined. Main then calls a method in another class file (that includes main's header so it should have access to the external variable), in order to print the value of that variable. But I get a compiler error: "unresolved external symbol "int myglobal". Can someone help? Thanks!
The code runs fine if I remove the reference to this variable in the source.cpp file.
source.cpp
#include "main.h"
#include <iostream>
void printGlobal()
{
std::cout << "Global: " << myglobal;
}
source.h
void printGlobal();
main.h
extern int myglobal;
main.cpp
#include "main.h"
#include "Source.h"
int main()
{
int myglobal = 5;
printGlobal();
system("pause");
return 0;
}
extern only works with global scope. if I say extern int myint; that means there is a file somewhere that has int myint; outside any function this is global scope
there is also file scope which is via static int myint; that means other files won't be able to access it via extern
change main.cpp to
#include "main.h"
#include "Source.h"
int myglobal = 5;
int main()
{
printGlobal();
system("pause");
return 0;
}
for file scope
#include "main.h"
#include "Source.h"
static int myglobal = 5;
int main()
{
printGlobal();
system("pause");
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With