must we always do
extern int a;
when declaring and not defining in C++?
Printable View
must we always do
extern int a;
when declaring and not defining in C++?
Do not use extern all the time. You need it only in some case that you do not have to define it but only to declare the variable.
Would you like to post a situation like that please?
Code:// in source file A
unsigned long x;
The extern keyword in the variable declaration means that we are NOT declaring the variable here, but that it is declared somewhere else. The compiler says, Ok, and happily compiles, and leaves it to the linker to find the variable it should be pointing to.Code:// in source file B
extern unsigned long x;
...
x = 10;
Z.
But.
It has to be a global variable.
ie., it is not defined inside any function, including main();
does that mean whenever I defining a extern, unsigned variable, I always have to define it outside any function?
I don't think so. But the actual variable you want to use should be global.Quote:
Originally posted by prog_tom
does that mean whenever I defining a extern, unsigned variable, I always have to define it outside any function?
So this one should be global if you want to use extern:
Where this one can be anywhere as long you follow the above rule(I think):PHP Code:int myvar;
PHP Code:extern int myvar;
No. It should be global as well in the sub-module.