Why I declare an extern variable in header file but it still can't be used as global??

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.

Thanks in advance.

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>

extern int 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).
Thanks very much for answer.

I have another question, if I have another cpp file (c.cpp), which also includes a.h.
I have defined the bb in a.cpp in global scope.

So in this case, inside c.cpp, I can still use bb and its value should be 10, correct?

I should not define the bb in c.cpp again since it will cause the multi definition error, correct?
Correct.
Thanks very much.
Topic archived. No new replies allowed.