Declaration and definition of global variables in C + +

Source: Internet
Author: User

Original link: http://blog.csdn.net/candyliuxj/article/details/7853938

(1) Compilation unit (module)

After compiling the code on VC or VS, and clicking the Compile button to prepare the EXE file, the compiler does two steps:

The first step: compile each. cpp and the corresponding. h file into an obj file;

Step two: Link the project's obj file to generate the final. exe file.

As a result, errors can occur in two places:

One is the error that occurs at compile time, mainly is the syntax error;

One is the error at the time of the link, mainly is the repetition definition variable and so on.

The compilation unit refers to each obj file that is generated during the compilation phase.

An obj file is a compilation unit.

A. cpp and its corresponding. h files together form a compilation unit.

A project consists of a number of compilation units, each of which contains the relative address of the variable store, and so on.

(2) Declaration and definition of variables

When a function or variable is declared, it does not give it the actual physical memory space, it sometimes guarantees that your program compiles through; When a function or variable is defined, it has the actual physical space in memory.

If the external variable that you reference in the compilation unit is not defined anywhere in the project, even if it is passed at compile time, the link will be error-free because the variable is not found in the program's in-memory.

A function or variable can be declared more than once, but only once.

(3) The role of extern

Function One: When it is in conjunction with "C", such as extern "C" void fun (int a, int b), the compiler will compile the function name of fun by C rules to translate the corresponding function name instead of C + +. Function Two: When it does not modify the variable or function together with "C", as in the header file, the extern int g_nnum; Statementof a function or variable. function Range, its declared functions and variables can be used in this compilation unit or in other compilation units. That is, when the B compilation unit refers to the global variable or function defined in the a compilation unit, the B compilation unit contains only the header file of the a compilation unit, and at compile time, the B compilation unit cannot find the function or variable, but it does not error, it will find this function from the target code generated by the a compilation unit at the link. (4) There are two classes of global variables that require the use of common variables, and we define these variables as global variables. For example, Res.h and res.cpp respectively declare and define global variables, classes Producerthread and consumerthread to use global variables.
1 /**********res.h declaring global variables ************/  2 #pragmaOnce3   4#include <QSemaphore>5   6 Const intG_ndatasize = +;//total amount of data produced by producers7 Const intG_nbuffersize = -;//size of the ring buffer8   9 extern CharG_szbuffer[];//Ring BufferTen externQsemaphore g_qsemfreebytes;//the idle area that controls the ring buffer (refers to the area where the producer has not populated the data, or the area that the consumer has already read) One externQsemaphore g_qsemusedbytes;//control the usage area in the ring buffer (refers to the area where the producer has populated the data but the consumer has not read it) A /**************************/  

In the code above, G_ndatasize, g_nbuffersize are global constants, and others are global variables.

1 /**********res.cpp defining global variables ************/  2 #pragmaOnce3#include"Res.h"  4   5 //Defining global Variables6 CharG_szbuffer[g_nbuffersize]; 7 qsemaphore g_qsemfreebytes (g_nbuffersize); 8 Qsemaphore g_qsemusedbytes; 9 /**************************/  

When you use a global variable in another compilation unit, you include only the header file.

1 /*The ********* class Consumerthread uses global variables ************/  2#include"consumerthread.h"  3#include"Res.h"  4#include <QDebug>5   6Consumerthread::consumerthread (qobject*parent)7 : Qthread (parent) {8   9 }  Ten    One Consumerthread::consumerthread () { A    - }   -    theconsumerthread::~Consumerthread () { -    - }   -    + voidConsumerthread::run () { -       for(inti =0; i < g_ndatasize; i++) {   + G_qsemusedbytes.acquire ();  AQdebug () <<"Consumer"<<g_szbuffer[i%G_nbuffersize];  atG_szbuffer[i% g_nbuffersize] =' ';  - g_qsemfreebytes.release ();  -             -      }   -Qdebug () <<"&&consumer over";  - }   in /**************************/  
      You can also put the declaration and definition of a global variable together, which prevents you from forgetting the definition, such as the above extern char g_szbuffer[g_nbuffersize]; The file that references it is then replaced by the # include "Res.h" into the extern char g_szbuffer[];.     But this is not good because you cannot use # include "Res.h" (using it, if it reaches two or more, there is a redefinition error; Note: Even if you add #pragma once in res.h, or #ifndef duplicate definitions, Because each compilation unit is separate, it is defined separately, and you cannot use any of the other functions or variables declared by res.h, unless you also use extern adornments, which is too cumbersome, so it is recommended to use the. h declaration, as defined in. cpp. (5) Static global variables    note using the static modifier variable, you cannot use extern to decorate, that is, static and extern cannot occur at the same time. The Declaration and definition of a global variable for     static modification occurs at the same time, that is, when you declare a global variable with static in the header file, it is also defined. The scope of the global variable for     static modification can only be a compilation unit of its own. When the other compilation unit uses it, it simply copies its value to the other compilation unit, and the other compilation unit saves it in another memory, and the other compilation unit modifies it without affecting its value at the time of definition. That is, when other compilation unit A uses it, its physical address, and other compilation unit B uses it, its physical address is not the same, A and B changes to it can not be passed to each other.     Multiple places refer to the header file where the static global variable resides, and there is no redefinition error because it opens up extra space for storage in each compilation unit. The following is an example of the Windows console application code:
1 /* **********res.h********* */  2 Static Char g_szbuffer[6"12345";   3 void Fun ();   4 /* ********************** */  
1 /***********res.cpp**********/  2#include"Res.h"  3#include <iostream>4 using namespacestd; 5   6 voidFun () {7       for(inti =0; I <6; i++) {  8G_szbuffer[i] ='A'+i; 9      }  Tencout<<g_szbuffer<<Endl;  One }   A /************************/  
1 /* **********test1.h********* */  2 void fun1 ();   3 /* ********************** */  
1 /***********test1.cpp**********/  2#include"Test1.h"  3#include"Res.h"  4#include <iostream>5 using namespacestd; 6   7 voidfun1 () {8 Fun (); 9   Ten       for(inti =0; I <6; i++) {   OneG_szbuffer[i] ='a'+i;  A      }   -cout<<g_szbuffer<<Endl;  - }   the /************************/ 

1 /* **********test2.h********* */  2 void fun2 ();   3 /* ********************** */  
1 /***********test2.cpp**********/  2#include"test2.h"  3#include"Res.h"  4#include <iostream>5 using namespacestd; 6   7 voidfun2 () {8cout<<g_szbuffer<<Endl; 9 }  Ten /************************/  

1 /***********main.cpp**********/  2#include"Test1.h"  3#include"test2.h"  4   5 intMain () {6 fun1 (); 7 fun2 (); 8   9System"PAUSE"); Ten      return 0;  One }   A /************************/  

The results of the operation are as follows:

According to our intuitive impression, the results of the FUN1 () and fun2 () outputs are all abcdef, but actually the fun2 () output is indeed the initial value.     Then we follow the debug, found Res, test1, test2 G_szbuffer address are different, respectively, 0x0041a020, 0x0041a084, 0x0041a040, which explains why not the same. Note: When a static global variable is generally defined, it is placed in the. cpp file instead of the. h file, which does not cause unnecessary information pollution to other compilation units.    (6) When a global constant (const) const is used alone, its properties are the same as static (the address in each compilation unit is different, but because it is a constant and cannot be modified, there is no significant relationship). When const is used with extern, its properties are the same as extern.
1 extern Const Char g_szbuffer[];      // written in  . h 2 Const Char " 123456 " // written in  . cpp

Declaration and definition of global variables in C + +

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.