I have a header file (a.h) and source file (a.cpp). In the header file, I declare an extern variable:
extern int bb;
In my source file, I have mutiple functions (e.g.: 5 functions). All these function use this variable. Then I define this variable in the main function:
int bb = 10;
I think this variable should be global, since it is declared in header file as extern. But when I run the code, I can see errors which reported that "bb" has not be defined in the functions (except main function). So my question is why "bb" is not global even I declared it in the header file as extern? I did include a.h in my a.cpp.
Variables declared inside function bodies are local. Period. That you also declared a global variable with the same name is irrelevant. They may have the same name, but the variables are separate.
1 2 3 4 5 6 7 8 9
#include <iostream>
externint bb;
int main(){
int bb = 10;
//Always prints "1":
std::cout <<(&bb != &::bb)<<std::endl;
}
To define the global, you need to put the definition in global scope (i.e. outside of any function).