#include <iostream>
usingnamespace std;
externint ei;
int i;
int ic=1;
int main() {
//int *pei=&ei;
//cout<<pei<<endl;
ei=1;
int *pei=&ei;
cout<<pei<<endl;
int *pi=&i;
cout<<pi<<endl;
i=1;
pi=&i;
cout<<pi<<endl;
int *pic=⁣
cout<<pic<<endl;
i=2;
pic=⁣
cout<<pic<<endl;
return 0;
}
Others are all fine in this program except ei.
compiler error: undefined reference to ei.
I understand ei is only declared so there is no memory address, but when I do ei=1, then ei completed it's definition, why still cannot use pei to get it's address? Thanks.
Thanks, rich1, but if I want the variable be visible across many files, I have to declare it in a header file, and then include the header in those cpp files, right? Then I cannot define it, I have to use extern to declare it, right? Otherwise there will be mutiple definition error!
I guess I got it, I just need to define the ei outside any function, that will not create any new variable, and the declared ei will be really defined!!! Am I right?
I couldn't erase this contribute, so I just edit it. I'm sorry for misleading you, I will "measure twice cut one" next time. And also, MikeBoy, thank you for your explanation.
You've got that the wrong way around. You don't want to put the actual definition in a header file - because then every translation unit that contains that header will be attempting to define the global, leading to errors caused by multiple definitions.
The definition should be done in one single source file.
Meanwhile, the extern declaration needs to be part of every translation unit that needs to access that global variable, so it's entirely suitable to put it in a header.
Of course, the best advice is to avoid using global variables wherever possible. They're highly problematic, and are almost always a bad idea.