c ++ extern keyword and global variable

extern role: used to declare variables before, indicating that this is a declaration rather than a definition, the specific definition is in another file.

int a; // This is the definition

int a = 1; // This is also the definition

extern int a; // This is the declaration

extern int a = 1; // This is the definition, extern is useless.

A variable can only be defined once and can be declared multiple times .

 

What should I do to make a variable a global variable ? That is: want to define a global variable in a file, and then be accessible in other files.

Global variables: defined in a file, and then extern declare this variable in another file, it can be used in this file.

E.g:

In test.cpp:

int a = 1;

There are two ways to use the variable a in other files:

(1)

In main.cpp:

extern int a;

int b = a; // A can be used. Include is not used here, but the compiler knows to find the definition of a in another file.

(2)

In main.cpp:

include “test.cpp”

int b = a; // This can also be used, because include is equivalent to merge the include file into this file.

There is a problem with method two. When multiple files want to use this global variable a, include this file multiple times, so that a is repeatedly defined multiple times, and the compiler reports an error: repeated definition.

 

Generally in C ++, variables and functions are defined in the cpp file (defined in the header file, if it is included multiple times will be repeatedly defined), and then the defined things are declared in the header file of the same name, so when using this file Just look at the concise header file.

So generally there is extern int a; in test.h; // extern is a statement

Then in test.cpp, include "test.h". In this way, the variable a defined in cpp is the a declared in the header file.

If test.h will be included twice or more, then this extern must be added, if not, it is defined, as mentioned in the opening chapter.

When you want to use the global variable a in another file:

method one:

extern int a;

Method Two:

include "test.h" // Because there is extern int a in this header file;

Method two is more in line with habits. In general, C ++ object-oriented programming rarely has separate global variables exposed outside the class, so if there are global variables, they are put into a cpp file, defined in this file, and then declared in the header file of the same name. To use these global variables, include this header file.

 

 

Published 59 original articles · Likes46 · Visits 30,000+

Guess you like

Origin blog.csdn.net/sinat_41852207/article/details/104804588