declare and storage allocate?

decalration won't allocate storage, while definition will. This is a test program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

extern int 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=&ic;
	cout<<pic<<endl;
	i=2;
	pic=&ic;
	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.

Last edited on
ei=1 does not define the variable, even though it assigns something to it. You need int ei; somewhere in your program, either in this file or another.
Thanks! If I do int ei=1; in the main() program, that will create a new ei and overlap replace the global ei. How can I define it?
Last edited on
define the global variable without extern
then if you want to use it in the function, write ::ei
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!
Last edited on
yes, use extern and don't forget to use :: to distinguish local and global variables
Then how can I define the global declared ei?
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.
Last edited on
@rich1

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.
Last edited on
Topic archived. No new replies allowed.