I'm trying to understand how exactly extern works in C++. There are many questions asked about this keyword on StackOverflow but none of them clarifies my problem:
Situation 1
AuxSource.cpp
int GlobalVar = 5;
Source.cpp
#include <iostream>
#include <conio.h>
#include "AuxSource.cpp"
int main()
{
std::cout << GlobalVar;
return 0;
}
ERROR: one or more multiply defined symbols found
ERROR: int GlobalVar
already defined in AuxSource.obj
// What the heck!? I defined it once!
Situation 2
AuxSource.cpp
int GlobalVar = 5;
Source.cpp
#include <iostream>
#include <conio.h>
#include "AuxSource.cpp"
extern int GlobalVar; // added
int main()
{
std::cout << GlobalVar;
return 0;
}
ERROR: one or more multiply defined symbols found
ERROR: "int GlobalVar"
already defined in AuxSource.obj
// Same errors.
Situation 3
AuxSource.cpp
int GlobalVar = 5;
Source.cpp
#include <iostream>
#include <conio.h>
// #include "AuxSource.cpp" - deleted
extern int GlobalVar;
int main()
{
std::cout << GlobalVar;
return 0;
}
// It works, but how is that possible?
Every tutorial out there uses the combination of including outer (non-main) file with some global variable and extern redeclaration + variable use in another module but it doesn't work for me. Either I still don't comprehend the concept of extern or something's wrong with my VS2013 (much less likely).