Skip to main content
gamedev.net
🔒 Locked

Global Variable

Started by Tauqeer May 6, 2004 at 11:42 AM 2 replies 350+ views
Original Post
Tauqeer
Tauqeer
the problem is like this i have created a class in VC++ named CMyInput and then i include it in CMyApplication which is another class when i declared a global variable in MyInput.h compiler created an error of (variable is already defined in MyApplicaion.obj) how can i use a variable such like this thanks in advance
Coincoin
Coincoin
First, you should ensure your include files are never included twice by putting that in our header. Also, you must ensure that interdependent classes don''t posses an instance of each others.


Use this first solution if your project is big, it will reduce dependencies.

#ifndef _MYHEADERFILENAME_H_
#define _MYHEADERFILENAME_H_
class MyClassName {
//declarations go here.

};
#endif


Also, in dependent headers, avoid including .h as much as possible. Use forward declarations instead like this.

class MyClassName;
class MyDependentClass {
MyClassName* blah; //you can also use a reference, but not an instance

}



---------
If your project is small, you can do that automatically in the header file and include the header in dependent headers, like this:


#ifndef _MYCLASSNAME_CLASS_
#define _MYCLASSNAME_CLASS_
class MyClassName;
#endif

#ifndef _MYHEADERFILENAME_H_
#define _MYHEADERFILENAME_H_
class MyClassName {
//declarations go here.

};
#endif


However, this will create a LOT of dependencies and your whole project will recompile everytime you make a change in one .h
Arild Fines
Arild Fines
While Coincoin had a lot of good general advice, he didn''t really answer your question. If you really need to put a global in a header, this is what you do(exclusion guards etc omitted for brevity - see Coincoins post):

In the header:

extern int Global;


This tells the compiler that there is a variable named global, but that it shouldn''t allocate memory for it since it is declared elsewhere.

Then, in exactly *ONE* of the .cpp files - doesn''t really matter which:


// file1.cpp
int Global;


This will allocate the actual memory needed to hold that variable.

--
AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.
[Project site] [Blog] [RSS] [Browse the source] [IRC channel]
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.