How to define global variables in VC

Source: Internet
Author: User

Q: How do I define global variables in VC?

A:
Put in any file
Use extern declaration in other files
Or declare a Public Member in the App class.
It can be used in other classes of the program.
AfxGetApp () gets an App object pointer and converts it to your App class pointer.
Then you can use the pointer-> variable
In addition
The class defined in MFC only for static members can be directly applied at that time.
Damaged Structure

A: You can also create a. h header file to store global variables. If you want to use it, just Include it.

//////////////////////////////////////// ///////////////

Reply
 
Lizhongjun1984
19 fans
2nd floor
Global variables in VC ++)
Http://blog.csdn.net/znsky/archive/2008/01/05/2026747.aspx

Global variables are generally defined as follows:
1. Define int myInt in Class 1. cpp;
Then, use extern int myInt in. cpp where you want to use it.

2. Add the following to stdafx. cpp:
Int Myint;
Then add the following to stdafx. h:
Extern int Myint
This definition will be visible in any file.

3. It is more standardized to define a glbs. h and put the original definitions of all global variables in it. Define an externs. h and add extern to all the variables you previously defined in glbs. h. Note: If you set an initial value in glbs. H, do not add a value to externs. h. The # I nclude <glbs. h> that is called for the first time and the # I nclude <externs. h> that is called later

In addition:

Q: How to Use global variables in VC ++ so that all classes in the document can be accessed.
A: place the variable in the attribute field in the header file of the application class. Then, anywhere in the program, you can use the following method to access the variable:
Cmyapp * APP = (cmyapp *) afxget-app ();
App-> myglobalvariable =...
This method can be used to define both global variables and global objects.
For example:
Myclass myobject;
Cmyapp * APP = (cmyapp *) afxget-app ();
App-> myobject. myfunction ();

Two methods for using global variables in VC and Error Prevention Measures

1. Global variables are the same as functions. to access these variables in other CPP files, you must add the extern declaration in the H file of the main file. The format is as follows:
Extern varibletype var; (Declaration)
Defined in the CPP file of the main file
Varibletype var; (defined)
Example:
Appwizard creates a test project
Declare extern cstring CS in test. h;
Define cstring CS in test. app;

If you want to define the global variables of the entire project, define them in any CPP file and declare them in the file that needs to reference this variable. For example, many global variables can be used to define global variables. H file, you can directly include the header file as needed, and do not need to write so many extern files.

2. The main header file of the application class defines the variable varibletype var. Then, you can access the variable anywhere in the program using the following method:
Cclassapp * APP = (cclassapp *) afxgetapp ();
App-> Var =
Similarly, the above method can also define global objects.
Example:
Appwizard creates a test project
Declare cstring CS in test. h;
When using ctestapp * APP = (ctestapp *) afxgetapp ();
App-> cs = "Global"

Troubleshooting measures:
If the defined function and global variable are included in multiple files and cause nesting or multiple calls, this will cause the header file to be included in sequence and the function or variable to be redefined once, during link compilation, a redefinition error occurs. Therefore, a technology called guard macro is required to ensure that no error occurs. Add

# Ifndef _ macro_1 _
# DEFINE _ macro_1 _
Add at the end of the file
# Endif

In addition, a friend wrote a definition of global variables in MFC.

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

A project created using MFC is composed of many files. It cannot define global variables as in General C ++ programs, to define global variables and functions that can be shared by multiple files in the project, you must use some special methods. There are actually many ways to implement it. Here we only introduce two methods.

1. Define in the application class

In the project generated using MFC, there is a class named cxxxapp, which is derived from the cwinapp class. This class mainly initializes the program and generates documents and view objects. We can define the variables and functions that require global access as member variables and member functions of this class to implement global access.

Strictly speaking, such variables and functions are not global, because they are still only members of the class, just because we can easily obtain pointers to the cxxxapp class, therefore, you can access them in documents, views, dialog boxes, and various custom classes to achieve the same effect as global variables. Use the function "afxgetapp ()" to obtain the cxxxapp class pointer and use "afxgetapp ()-> member" to access the variable or function.

Reply
 
Lizhongjun1984
19 fans
Third floor

Example:

Test. h: (Application Class header files)

Class CTestApp: public CWinApp
{
Public:
Int x; // global variable
Int f (int y); // global function
............
};
Test. cpp: (application program files)

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, to access the variables x and f () in a function of a view ():

Void CTestView: xyz ()
{
CTestApp * app = (CTestApp *) AfxGetApp (); // generates a pointer to the application class
App-> x = 0; // access variable x
Int z = app-> f (1); // access function f ()
............
}
In this way, the variables x and function f () can be regarded as global.

The global variables and global functions implemented in this method are relatively simple, but they also have disadvantages. First, they are not easy to access and need to obtain the pointer of the application class each time; then, we put some variables and functions irrelevant to the application class itself in it, which makes the class look strange and destroys the class encapsulation.

2. Use static variables and static functions

I like the calling method of API functions. No matter which class I use, I can call the method by using ": API function. Reasonable Use of static can achieve similar global variables and global functions.

Static variables and static functions have the following properties:

If a data member is declared using the static keyword in a class, only one copy exists for this data member. No matter how many instances are created for this class, only one copy exists, even if no instance of this class is created, it also exists.

If a function is declared using the static keyword in a class, the function can be accessed using the "Class Name: function name" method, without reference to the instance of this class, or even the instance of this class can not exist.

It is convenient to use global variables and functions implemented using this property.

It is worth noting that it is best to encapsulate global variables and global functions in a centralized manner. do not define them in documents, views, and other classes so that they can be used globally.

Example:

1. Add a new class without a base class and set the class name to CPublic.

Click the "New Class" command under the "Insert" menu, select "Class type" as "Generic Class", and enter the Class Name "CPublic" in the "Name" column ", click OK. The new class is created.

2. Include the header file of the public class so that each class can access it

The header file of CPublic should be included in the header file of the application class, so that the CPublic class does not need to be included when it is referenced in other classes.

Test. h: (Application Class header files)

# Include "Public. h" // contains the Public Class header file

Class CTestApp: public CWinApp
{
............
};
3. global variables and global functions are defined in the public class and modified using static. static variables must also be defined and initialized outside the class.

Public. h: (Public Class header files)

Class CPublic
{
Public:
CPublic ();
Virtual ~ CPublic ();

Public:
Static int x; // global variable
Static int time; // global variable
Static int f (int y); // global function
............
}
Initialize and define the static variables in the public class:

Public. cpp :( Public program file)

Int CPublic: x = 0; // initialize the global variable
Int CPublic: time; // defines the global variable

CPublic: CPublic ()
{

}

CPublic ::~ CPublic ()
{

}

Int CPublic: f (int y) // global function. Do not add static
{
Y ++;
Return y;
}
4. Global usage

Use the variable CPublic: variable name

Use Function: CPublic: function ()

For example, access the variables x and f () in a function in 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. Notes:

① Because the static volume can exist independently of the class, instances of the CPublic class do not need to be generated.

② The definition and initialization of static data members must be performed outside the class, such as the initialization of x in the example. Although the variable time is not initialized, it must also be defined outside the class. Because no CPublic class instance is generated, its constructor and destructor are not executed, and it makes no sense to do anything in it.

③ If a static function needs to access the variables in the CPublic class, these variables must also be static. Because the non-static volume does not exist when the instance is not generated. For example:

Class CPublic
{
Public:
Int x; // internal variable
Static int f (int y) // global function
{
X ++;
Return x;
};
............
};
Although x is a member of the class, if you do not generate an instance of the CPublic class, the f () function will exist, and the variable x does not exist.

In short, managing the global volume of classes without instances is a good choice. It has the advantages of centralized management and ease of use. Of course, unless necessary, it is better to reduce the global volume. A good programmer will never abuse the global volume at will, and a program that is encapsulated and not done well, modification and maintenance will make you suffer.

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.