where can i declare a global variable to use it in different classes. thanks
Printable View
where can i declare a global variable to use it in different classes. thanks
Global variables need to be declared in the header and be defined in one .cpp file...e.g.
However, usually you would avoid using globals...why do you need one in the first place?Code:// global.hpp
extern int iInt;
// global.cpp
int iInt;
in afxstud.h
CString str1;
then use as
extern CString str1; where ever u want( other classes);
*** enjoy in programming***
ravirams ,
i am using connection variable in a way you said
but i am getting following errors
x8086Code:Linking...
DataBaseView.obj : error LNK2005: "class _com_ptr_t<class _com_IIID<struct _Connection,&struct __s_GUID _GUID_00000550_0000_0010_8000_00aa006d2ea4> > pConnection" (?pConnection@@3V?$_com_ptr_t@V?$_com_IIID@U_Connection@@$1?_GUID_00000550_0000_0010_8
000_00aa006d2ea4@@3U__s_GUID@@A@@@@A) already defined in DataBase.obj
DBFunctions.obj : error LNK2005: "class _com_ptr_t<class _com_IIID<struct _Connection,&struct __s_GUID _GUID_00000550_0000_0010_8000_00aa006d2ea4> > pConnection" (?pConnection@@3V?$_com_ptr_t@V?$_com_IIID@U_Connection@@$1?_GUID_00000550_0000_0010_80
00_00aa006d2ea4@@3U__s_GUID@@A@@@@A) already defined in DataBase.obj
Debug/DataBase.exe : fatal error LNK1169: one or more multiply defined symbols found
Error executing link.exe.
What is your variable name?Quote:
Originally Posted by x8086
From the error messages you showed us, it could be caused by "multiple declaration of variable".
All "extern" statements can be included in all ".h" or ".cpp":
But there must be one normal declaration in either ONE (and only one) ".cpp" or in a ".h" in which the contents are used by only one ".cpp":PHP Code:// global.hpp
extern int iInt;
if the normal declaration is made in a ".h" file, and this file is included by a ".h" that is included by many ".cpp", you will also get the same error.PHP Code:// global.cpp
int iInt;
Let it be simple:Defining let the linker (not the compiler) put the variable into executable, at global level. If you 'define' a variable many times, linker will already find in other object file (since you may have defined in the respective source file) and will compain you the same.
- You declare as variable as extern many times, as many times you wish to refer in source files.
- You define the variable only once across all source files.
As pointed out by Ajay Vijay, there are differences between declaration and definition, which I overlooked and probably messed up in my previous post, I am sorry about my misleading post, please refer to Ajay Vijay's post which is more precise and neat.
p/s: thank you, Ajay Vijay ;)