Welcome: Hunan Intelligent Applications Tecgnology CO.,ltd.-HNIAT.com
Language: Chinese ∷  English

Basic knowledge

How to share a global variable in multiple files

example:

Header: state.h Source: state.cpp

 Other source files: t1.cpp t2.cpp t3.cpp, these source files include the header file state.h.

Need to define a global variable for use in these source files: The method is as follows

1. Declare global variables in state.h: extern inta;

2. Define the global variable in state.cpp: int a = 10;

So other source files can use this variable

 

 

What is needed here is "declaration", not "definition"! According to the C ++ standard, a variable declaration must satisfy both conditions, otherwise it is defined:
 (1) The statement must use the extern keyword; (2) You cannot assign an initial value to a variable
  extern int a; // declaration


 int a; // definition

 int a = 0; // definition

 extern int a = 0; // definition

 

 

     Header files should use the extern keyword to declare global variables (undefined). If this variable is used in multiple files, you can create a new cpp, define it in it, and add this cpp to the project. Please do not define any variables in the header file, that is very amateurish behavior ...

    Generally stated in the header file, use extern, defined in cpp. If it is defined in a header file, if this header file is referenced by multiple cpps, it will cause a linking error of duplicate definitions.

    The header file can only declare global variables (extern) and cannot be defined (not recommended). In the .cpp, it can be defined in the outermost layer (int gi) and directly referenced

If you use static definition in .cpp, this variable is only valid in the current cpp file, and it is invalid in other files
Using static definitions in .h does not compile (the .h files are not compiled), it only includes compilation in each of its include cpp files, which is equivalent to using static definitions in .cpp.

Reprinted: http://www.cnblogs.com/yyxt/p/3891712.html

1 Basic explanation: Extern can be placed in front of a variable or function to mark the definition of the variable or function in another file, prompting the compiler to find its definition in other modules when it encounters this variable and function. Extern can also be used to specify links.

      In other words, extern has two functions, the first one, when it is used together with "C", such as: extern "C" void fun (int a, int b); tells the compiler to compile fun this function name Translate the corresponding function name instead of C ++ according to the rules of C. The rules of C ++ will change the name of fun to something completely different. It may be fun @ aBc_int_int #% $ or something else. This requires Look at the "temper" of the compiler (different compilers use different methods), why do you do this, because C ++ supports function overloading? I won't go into too much about this issue here, if you are interested, you can Go online and believe that you can get a satisfactory explanation! (C ++ and C use different name modification rules)
    Second, when extern does not modify a variable or function together with "C", such as in a header file: extern int g_Int; Its role is to declare the keywords of the scope of functions or global variables, and their declared functions and variables Can be used in this module and other modules, remember that it is a declaration and not a definition! That is, if module B (compilation unit) refers to a global variable or function defined in module (compilation unit) A, it only needs to include module A The header file is sufficient. Although module B cannot find the function or variable during the compilation phase, it will not report an error. It will find this function from the object code generated by module A at link time.

2 Problem: extern variables
数组 An array is defined in a source file: char a [6];
声明 Declared in another file with the following statement: extern char * a;
Excuse me, is this OK?
Answer and analysis:
1) No, the program will tell you illegal access when the program is running. The reason is that a pointer to type T is not equivalent to an array of type T. extern char * a declares a pointer variable instead of a character array, so it is different from the actual definition, causing illegal access at runtime. The declaration should be changed to extern char a [].
2) The example is analyzed as follows. If a [] = "abcd", then the external variable a = 0x61626364 (ASCII value of abcd), * a is obviously meaningless.
Apparently the space pointed by a (0x61626364) is meaningless and prone to illegal memory access.
3) This reminds us that when using extern, we must strictly correspond to the format of the declaration. In actual programming, such errors are common.
4) Extern is often used in variable declarations. You declare a global variable in the * .c file. If this global variable is to be referenced, it is placed in * .h and declared with extern.

3 Problem: Unilateral modification of extern function prototype
When the function provider unilaterally modifies the function prototype, if the user continues to use the original extern declaration without knowing it, the compiler will not report an error when compiling. However, during the running process, because there are fewer or more input parameters, it will often be a system error. How should this situation be resolved?
Answer and analysis:
At present, the industry does not have a perfect solution to this situation. The usual practice is that the provider provides an external interface declaration (extern) in its xxx_pub.h, and then the caller includes the header file, thereby eliminating the extern. This step. To avoid such errors.
Qi Baojian has two fronts. For the application of extern, different methods should be chosen for different occasions.

4 Question: extern "C"
使用 When using C functions in the C ++ environment, it often happens that the compiler cannot find the C function definition in the obj module, which causes the link to fail. How can we solve this situation?

Answer and analysis:
In order to solve the polymorphism of functions when compiling C ++ language, the function name and parameters are combined to generate an intermediate function name, while C language does not, so the corresponding function cannot be found at link time. C functions need to be specified with extern "C" for linking. This tells the compiler, please keep my name, and don't generate me intermediate function names for linking.
The following is a standard wording:

Copy code
Copy code
// on the header of the .h file
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#Endif
#Endif / * __cplusplus * /
Uh ...
Uh ...
//.H where the file ends
#Ifdef __cplusplus
#If __cplusplus
}
#endif
#endif / * __cplusplus * /
Copy code
Copy code
 

5 Problem: extern function declaration
It is common to place externs in front of functions as part of function declarations. So, what role does the C keyword extern play in function declarations?
Answer and analysis:
If the function declaration has the keyword extern, it only implies that the function may be defined in other source files and has no other effect. That is, there is no obvious difference between the following two function declarations:

extern int f ();

int f ();

Of course, there is still such a use, instead of including "* .h" in the program to declare the function, in some complex projects, I am more accustomed to add extern decoration before all function declarations. The reasons and advantages and disadvantages of this can be seen in the following example: "Global variables decorated with extern"

    (1) The following statement is in test1.h:

    #ifndef TEST1H
    #define TEST1H
    extern char g_str []; // declare global variable g_str
    void fun1 ();
    #endif
    (2) in test1.cpp

    #include "test1.h"
        char g_str [] = "123456"; // define global variable g_str
        void fun1 () {cout << g_str << endl;}
    (3) The above is the test1 module, which can be compiled and linked. If we still have the test2 module and want to use g_str, just reference it in the original file.

    #include "test1.h"

     void fun2 () {cout << g_str << endl;}
    The above test1 and test2 can be compiled and linked at the same time. If you are interested, you can open test1.obj with ultraEdit. You can find the string "123456" in it, but you cannot find it in test2.obj. This is because of g_str It is a global variable of the entire project. There is only one copy in memory. There is no need to have another copy of the compilation unit test2.obj, otherwise this error will be reported repeatedly during connection!

Note: If sizeof is used, the size of the declared array needs to be specified extern char g_str [7]; Because the test2 module only declares an array, the specific size is unknown. If the array size is not declared in the .h file, an "illegal sizeof operand" error will be reported.

(4) Some people like to put the declaration and definition of global variables together, this can prevent forgetting the definition, such as changing test1.h above to
   

extern char g_str [] = "123456"; // this time is equivalent to no extern
    Then remove the definition of g_str in test1.cpp. At this time, when compiling and connecting the two modules test1 and test2, a connection error will be reported. This is because you put the definition of the global variable g_str after the header file, test1.cpp This module contains test1.h so it defines g_str once, and test2.cpp also contains test1.h so it defines g_str again. At this time, the connector finds two g_str when connecting test1 and test2. If you have to put the definition of g_str in test1.h, then replace #include "test1.h" in the code of test2 with:

extern char g_str []; // no include "test1.h"
void fun2 () {cout << g_str << endl;}

   At this time, the compiler knows that g_str is an externally compiled module. It will not be repeatedly defined in this module, but I want to say that this is very bad because you cannot use it in test2.cpp # include "test1.h", then you cannot use other functions declared in test1.h, unless you also use extern to modify them. In this case, the functions you declare will be a long list, and the function of the header file is to give Externally provided interfaces are used, so keep in mind that only making declarations in header files, truth is always so simple.

6. extern and static

 (1) extern indicates that the variable has been defined elsewhere, and that variable is used here.
 (2) static indicates a static variable. When memory is allocated, it is stored in the static area, not on the stack.

    The scope of static is an internal connection relationship, which is a bit opposite to extern. It is stored separately from the object itself, and extern is also stored separately, but extern can be referenced by other objects using extern, while static cannot, only the object itself It ’s specific difference. First, static and extern are a pair of “incompatible” guys. That is, extern and static cannot modify a variable at the same time. Second, static global variable declaration and definition are performed at the same time, that is, when you are in After the global variable (external class) is declared statically in the header file (if the static variable is declared inside the class of the header file, its definition is usually located in the implementation (.cpp) file. The exception is that only const int types can be in class (Initial value setting), it is also defined at the same time; finally, the scope of the static modified global variable can only be its own compilation unit (internal link, see storage persistence, scope, and linkability), that is, its "Global" is only valid for this compilation unit, other compilation units cannot see it, such as:
    (1) test1.h:

#ifndef TEST1H
#define TEST1H
static char g_str [] = "123456";
void fun1 ();
#endif
    (2) test1.cpp:

#include "test1.h"
void fun1 () {cout << g_str << endl;}
    (

CONTACT US

Contact: Manager Xu

Phone: 13907330718

Tel: 0731-22222718

Email: hniatcom@163.com

Add: Room 603, 6th Floor, Shifting Room, No. 2, Orbit Zhigu, No. 79 Liancheng Road, Shifeng District, Zhuzhou City, Hunan Province

Scan the qr codeClose
the qr code