/*DON'T INCLUDE my.h*/
#include<iostream>
int main(int argc, char ** argv)
{
externint a;
std::cout<<a; //will output 500
return EXIT_SUCCESS;
}
Include directive does nothing smart, it just copies the contents of the header. Extern on the other hand tells the compiler to look for the variable in an external file
GoldenLizard has it backwards. Header files should contain declarations, but not definitions. The definition of a variable is basically where you allocate space.
BlueSquirrelJQX, the problem with your code is that you have declared the variable but you haven't defined it. The int foo at line 7 is a local variable, not the extern one declared in my.h.
Exactly one compilation unit must contain the definition, so just add that to source.cpp, or better yet, add it to my.cpp:
GoldenLizard has it backwards. Header files should contain declarations, but not definitions. The definition of a variable is basically where you allocate space.
That was only to exemplify it. I changed it to use a cpp file too, to be more correct