Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Global Variables - C++ Builder Newbie 1

Status
Not open for further replies.

StevenK

Programmer
Jan 5, 2001
1,294
0
0
GB
I'm new to C++ Builder and come from a Delphi development environment. I'm trying to create my first application (with something of a gung-ho attitude I'm afraid) and have a Global unit in the project with global variables defined in it (i.e. gbvUserID (integer), gbvUserKnownAs (String)). I'm probably missing the obvious but what do I need to do to enable other forms to access these global variables ?
I've tried declaring them in the .cpp file and the .h file and also made use of the extern keyword - however my other forms still return messages related to an unresolved external declaration - _gbvUserID. It's probably something simple - can someone give me a pointer ?
Thanks in advance.
Steve
 
I've found that the best place to initialize global variables is between the form declaration and initialization. I've seen some of Borland's examples do this, too. In other examples, I've seen the initialization in the form's initialization but I've had very limited succes with this.
Code:
TForm *Form;
//---------------------------------------------------------------------------
// Global Variables
// I put my globals here.
AnsiString DefaultDate = DateToStr(Date());
int DefaultRepeat = "1";
//---------------------------------------------------------------------------
__fastcall TForm::TForm(TComponent* Owner)  : TForm(Owner)
{
     // I've seen some put here, too.
}

One note: use global variables sparingly since they consume resoures like memory. If you have the examples installed, do a grep for "global" in *.cpp in the Borland directory.

James P. Cottingham
 
another example:

var.h:
//---------------------------
#ifndef __MY_VAR__ // It's very important!
#define __MY_VAR__
int myFirstVar;
// etc
// etc

#endif
//---------------------------


other forms:
man.cpp: // for example
//---------------------------
#include "var.h"

// the body of the man.cpp
//---------------------------







 
Thanks for the responses on this one people.
Another quick question on this matter - I was looking at using global variables to store global information (for instance the users information following log-on). Would I be better off creating a class and maintaining the same information in this ? Is this a more efficient (memory-friendly) way of achieving the same ends ?
Thanks again
Steve
 
If you have several variables relating to one conception (object), the best way is to use a class.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top