PDA

Click to See Complete Forum and Search --> : Global variable declare


Chris
Nov 17th, 2000, 07:33 AM
How can I declare a public variable in C++ (without MFC) and so that I can share this variable in two different cpp file.

example:
I have 2 variable name ptX and ptY both are double data type.
I need to store a value at runtime into this variable at a.cpp and use this value in b.cpp.

Thanks,
Chris.C

parksie
Nov 17th, 2000, 05:47 PM
Your variable is declared as normal in the first .cpp file. In the second, add an extern definition. For example:

file1.cpp

int iVar;


file2.cpp

extern int iVar;


Make sense? (I hope so! ;))

Chris
Nov 17th, 2000, 10:13 PM
can I do it in this way?

file1.h
double pt1;



file2.cpp
extern double pt1;

parksie
Nov 18th, 2000, 08:12 AM
If file2.cpp includes file1.h, then you don't need to do anything in file2.cpp, since it will have it. However, it's not usually a good idea to declare variables in a header. Unless, of course, it's an extern. In <iostream>, there is a definition of:

extern ... cout;

...because it refers to one thing all the way through all the code. Normally headers should only contain definitions of classes, types, structures, and as little code as possible. (You can put code in, but be careful)

Chris
Nov 18th, 2000, 08:38 PM
Thanks Parksie. I know how to improve my program already. Thanks a lot for your explaination.