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;
}