VC + + Global variables (RPM)

Source: Internet
Author: User

Global variables are generally defined like this:
1. Define int myInt in a class of. cpp;
And then in the place where you want to use the. cpp extern int myInt;

2. Add in Stdafx.cpp:
int myInt;
Then add in the stdafx.h:
extern int MyInt
This is defined later in whatever file is visible.

3. It is more canonical to define a Glbs.h and put all the global variables in the original definition. Then define a Externs.h and add extern to the variables you previously defined in Glbs.h. Note: If you set the initial value in Glbs.h, do not add values in the Externs.h. Then called when the first call to the #i nclude <glbs.h> #i nclude to be called later <Externs.h>

Other:

Q: How to use global variables in VC + + so that all classes in the document can be accessed.
A: Place the variable in the header file of the application class at attribute. Then, anywhere in the program, you can access the variable in the following way:
CMyApp *app= (cmyapp*) Afxget-app ();
App->myglobalvariable= ...
In this way, you can define global variables as well as global objects.
For example:
MyClass MyObject;
cmyapp*app= (cmyapp*) Afxget-app ();
App->myobject.myfunction ();

2 ways of using global variables in VC and anti-error measures

1. For global variables to have the same problem as functions, in order to be able to access these variables in other CPP files, the extern declaration must be added to the H file in the main file in the following format:
extern varibletype var; Statement
Defined in the CPP file of the main file
Varibletype var; Custom
Example:
AppWizard set up a test project
Then declare the extern CString CS in the Test.h;
Define CString CS in Test.app;

If you want to define a global variable for the entire project, define it in any CPP file and declare it in a file that needs to reference the variable. Many of the global variables can optionally be used to define global variables. h file, directly include the header file where needed, do not need to write so many extern.
2. The variable varibletype var is defined at the main header file of the application class, and then, anywhere in the program, you can access the variable in the following way:
Cclassapp *app= (cclassapp*) AfxGetApp ();
App->var=
Similarly, the above method can also define global objects
Example:
AppWizard set up a test project
Then declare CString CS in Test.h;
When used Ctestapp *app= (ctestapp*) AfxGetApp ();
App->cs= "Global"

Error-Proof measures:
If the defined functions and global variables are contained in multiple files and cause nested or multiple invocations, this will cause the header file to be included in sequence, and the function or variable will be redefined once, resulting in a redefinition error when the link is compiled. To do this, a technique called Guard macro is required to ensure that there is no error. At the beginning of a header file, add
#ifndef _macro_1_
#define _macro_1_
Add at end of file
#endif

Another one of my friends wrote. Defining global Variables in MFC

How to define global variables and global functions under MFC VC + +

MFC-made projects are composed of many files, it can not be like the General C + + program in the arbitrary definition of global variables outside the class, where you want to define the project can be shared by multiple files in the global variables and functions must be in some special way. There are actually a number of ways to do this, and here are just two methods.

One, defined in the application class

An MFC-generated project has a class named Cxxxapp, which is derived from the CWinApp class. This class primarily initializes the program, generating documents, view objects, and so on. We can implement global access by defining variables and functions that require global access as member variables and member functions of this class.

Strictly speaking, this variable and function is not global, because it is still only a member of the class, but because it is easy to get pointers to the Cxxxapp class, we can access them in documents, views, dialog boxes, and various custom classes to achieve a similar effect to global variables. Access uses the function "AfxGetApp ()" To obtain a pointer to the Cxxxapp class, and to access the variable or function with "AfxGetApp (), member".

Cases:

Test.h: (Application class header file)

Class Ctestapp:public CWINAPP
{
Public
int x; Global variables
int f (int y); Global functions
............
};
Test.cpp: (Application class program file)

int ctestapp::f (int y)//global function definition
{
y++;
return y;
}
Variables and functions defined in the Ctestapp class can be accessed in other classes. For example, in a function of the view to access the variable x and function f ():

void Ctestview::xyz ()
{
Ctestapp *app = (Ctestapp *) AfxGetApp (); To generate pointers to application classes
app->x = 0; Access variable X
int z = app->f (1); Access function f ()
............
}
In this way, the variable x and function f () can be considered as global.

The global variables and global functions implemented in this way are relatively simple, but there are drawbacks, one is that access is not convenient, each time you need to get pointers to the application class, and then put some variables and functions unrelated to the application class itself, so that the class looks strange, destroying the class encapsulation.

Second, using static variables and static functions to implement

Like the API function of the kind of call method, no matter in which class as long as ":: API function" can be called. A logical use of static types (statics) allows for similar global variables and global functions.

static variables and static functions have the following properties:

If you declare a data member with the keyword static in a class, there is only one copy of the data member, no matter how many instances the class creates, it always exists only one, even if the instance of the class is not created.

If a function is declared with the keyword static in a class, the function can be accessed using the "Class Name:: Function Name" method, without referencing an instance of the class, or even an instance of the class may not exist.

It is convenient to use the global variables and functions implemented by this nature.

It is important to note that global variables and global functions are best encapsulated and not defined inside classes such as documents, views, etc., so that you can use them to make a global impression.

Cases:

1, add a new class without a base class, set the class name as Cpublic, let's call it the common class

After clicking the "new Class" command under the "Insert" menu, select "Class type" as "Generic class" and fill in the "Name" field with the class name "Cpublic" and click "OK", the new class is established.

2, contains the common class header file, so that each class can access it

The header file of the Cpublic should be included in the header file of the application class so that it is not required to be included when referencing the Cpublic class in other classes.

Test.h: (Application class header file)

#include "Public.h"//contains common class header files

Class Ctestapp:public CWINAPP
{
............
};
3. Defining global variables and global functions in a common class, all using static modifiers, static variables must also be defined and initialized outside of the class

Public.h: (Common class header file)

Class Cpublic
{
Public
Cpublic ();
Virtual ~cpublic ();

Public
static int x; Global variables
static int time; Global variables
static int f (int y); Global functions
............
}
Initialize and define the function body in a common class for static variables:

Public.cpp: (Common class program file)

int cpublic::x = 0; Initializing global variables
int cpublic::time; Defining Global Variables

Cpublic::cpublic ()
{

}

Cpublic::~cpublic ()
{

}

int cpublic::f (int y)//global function, do not add static here
{
y++;
return y;
}
4, the use of global volume

Use variable: cpublic:: Variable name

Use function: Cpublic:: Function ()

such as accessing the variable x and function f () in a function of the view:

void Ctestview::xyz ()
{
cpublic::x = 0; Access variable X
Cpublic::time = Cpublic::f (1); Access function f ()
............
}
The methods for accessing X, Time, and F () in other classes are the same.

5. Note the following:

① you do not need to generate an instance of the Cpublic class because static quantities can exist independently of the class.

② the definition and initialization of a static data member must be done outside the class, such as the initialization of x in the example, while the variable time is not initialized but must also be defined outside the class. Since there is no instance of the Cpublic class, its constructors and destructors are not executed, and there is no point in doing any work in it.

③ if a static function needs to access variables within the Cpublic class, these variables must also be static. Because non-static quantities do not exist when the instance is not generated. Such as:

Class Cpublic
{
Public
int x; Internal variables
static int f (int y)//global function
{
x + +;
return x;
};
............
};
Here x is a member of the class, but if you do not generate an instance of the Cpublic class, there will be an issue where the function f () exists and the variable x does not exist.

In short, using a class with no instances to manage global volume is a good choice, it has the benefit of centralized management and easy to use. Of course, unless it is particularly necessary, the global volume is still less used as good, a good programmer will never arbitrarily misuse the global volume, a package does not do a bad program, in the modification of maintenance can make you suffer.

This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/znsky/archive/2008/01/05/2026747.aspx

Following BYMJF

If the global custom data structure variables are used in MFC and need to be initialized, add Global.h and Global.cpp files.

Global.h

typedef struct struct_mapman{
int isavewhere;//
int nplacetype;//

}struct_mapman, *lpstruct_mapman;

void Initialfun ();//The function that initializes the data structure must use the function to initialize the data structure.

extern Struct_mapman struct_mapman;//exported to other CPP files, just include "Global.h" in stdafx.h.

Global.cpp

Struct_mapman struct_mapman;//declaring global variables

Struct_mapman.isavewhere = 1; This is a compilation error, because it is not yet recognized Struct_mapman
void Initialfun ()
{
ZeroMemory (&struct_mapman,0);
Struct_mapman.isavewhere = 1;//operation OK in function, so initialize global struct variable in function declaration
}
The Initialfun function is then initialized in the desired class (most of the main interface classes).

VC + + Global variables (RPM)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.