The use of extern

Please tell me what's wrong with this period of code:

1
2
3
4
5
6
7
8
9
// code that goes into file "my.h":
extern int foo;

// code that goes into file "source.cpp":
#include "my.h"
int main()
{
int foo = 7;
}
something.cpp
 
int a=500;


source.cpp
1
2
3
4
5
6
7
8
9
10
/*DON'T INCLUDE my.h*/
#include<iostream>

int main(int argc, char ** argv)
{
 extern int 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
Last edited on
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:
1
2
#include "my.h"
int foo=7;

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
Last edited on
dhayden and Golden Lizard, thank you very much. I've modified my code and it works as desired now.
Topic archived. No new replies allowed.