[C + +] extern keyword explained and differs from static, const

Source: Internet
Author: User

An explanation of extern usage:

1. Declaring external entities

Declares an external global variable or object, typically used in a header file, that represents a variable defined within another compilation unit, and is linked with external links, such as:
extern int ivalue;
extern is required at this point, omitting the extern compiler as a definition rather than a declaration, typically defining variables in source code and initializing them, using extern declaration variables in the header file.

It is similarly used to declare an external global function, which means that the function is defined in other compilation units, such as:
extern void func (void);
The extern can be omitted at this time.

2. Declaring how functions are compiled and linked

extern can be followed by "C" or "C + +" to declare how the global functions are compiled and linked, for example:

 1  extern   " c   " void  Add (int  A, int   b);  2  extern   " c++   " void  sum (int  * ia, int   Leng);  3  void  sum ( int  * ia, int  Leng); 

The extern "C + +" can be omitted, it is the default link in C + +, that is, the following two declaration methods are equivalent. This declaration has two meanings: first, declaring that these functions use an external link, whose implementation is not within this compilation unit, or telling the compiler how to compile it, such as extern "C", which tells the compiler to compile the function using the C language.

C + + supports function overloading, so different parameters are generated after compilation with different function names, such as:

int max (int a, int b);
int Max (float A, float b);

The function names generated at compile time may be _max_int_int, _max_float_float, by adding parameter types after the function name to distinguish different functions, if you use the C language, the generated function name does not contain parameter information, only generates _max, so the overload cannot be implemented. This means that the function name overload cannot occur in extern "C", for example:

1 extern " C " {2     int max (intint  b); 3     int max (floatfloat  b); 4 }

Illegal, the compiler will error. The C + + standard does not define a specific implementation of extern "C" and extern "C + +", and different compiler-generated symbolic rules may be different.

Note that if the function declaration uses extern "C", the function definition must be compiled with the C compiler, or use the extern "C" To modify the way a function is compiled, it generally uses the source program extension where the definition of the function declared by extern "C" resides. C, and the C + + code is placed in the. cpp file. If the function implementation of the extern "C" declaration is also placed in the. cpp, you need to use extern "C" to declare how the function is compiled, for example:  

1 extern " C " {2     int int int b) 3     {4         return a > B a:b; 5     }6 }

The extern "C" is only used in C + + in a library or in two languages, and the extern "C" is not supported in the C language, so it is necessary to use macros to control the header files, for example:

1#ifndef Max_h//Prevent duplicate references2 #defineMax_h3 #ifdef __cplusplus4 extern "C" { 5 #endif 6 intMax (intAintb); 7 #ifdef __cplusplus8 } 9 #endif Ten #endif 

Where __cplusplus is defined as a C + + macro, the compiler for C + + defines the precompiled macro, which detects whether the current compiler is using the C + + compiler.

extern and Static comparisons:

(1) Extren indicates that the variable has been defined elsewhere, and that variable is used here.

(2) static variable, when allocating memory, is stored in the static zone, not stored on the stack.

The static scope is the internal connection, and the extern is somewhat opposite. It is stored separately from the object itself, and extern is stored separately, but extern can be referenced by other objects with extern, and static cannot, only allow the object itself to use it.

Specific differences: First, static and extern is a pair of "fire and Fire" of the guy, that is, extern and static can not modify a variable at the same time , and second, thestatic modification of the global variable declaration and definition at the same time , That is, when you declare a global variable with static in a header file, it is defined at the same time, and finally, the scope of thestatic modifier global variable is only its own compilation unit , that is, its "global" is only valid for this compilation unit, and other compilation units do not see it, such as:

(1) Test.h:

1 #ifndef test1h 2 #define TEST1H3staticchar"123456"; 4 void fun1 (); 5 #endif

(2) Test1.cpp:

1 " test.h " 2 void fun1 () 3 {4     cout << g_str << Endl; 5 }

(3) Test2.cpp

 1  #include  " test.h   " 2  void   fun2 ()  3  {  4  cout << g_str << Endl;  5 } 

The above two compilation units can be connected successfully, when you open test1.obj, you can find the string "123456" in it, you can also find them in the test2.obj, they can be connected successfully without reporting the duplicate definition of the error is because Although they have the same content, the physical address of the store is not the same, as if two different variables were assigned the same value, and the two variables were used for their respective compilation units. Perhaps you are more serious, your own secretly tracking debug the above code, and you find that two compilation units (TEST1,TEST2) of the G_STR memory address is the same, so you conclude that static modified variables can also act on other modules, but I want to tell you, That's your compiler is cheating you, most compilers have the ability to optimize the code to achieve the generated target program more memory saving, more efficient execution, when the compiler is connected to each compilation unit, it will be the same content of memory only one copy, such as the above "123456", The variable in the two compilation unit is the same content, then it will only exist in memory at the time of connection, if you change the above code to look like this, you can immediately expose the compiler's lies:

(1) Test1.cpp:

1 " test.h " 2 void fun1 () 3 {4     g_str[0'a'; 5     cout << g_str << Endl; 6 }

(2) Test2.cpp

1 " test.h " 2 void fun2 () 3 {4     cout << g_str << Endl; 5 }

(3) Main

1 void Main () 2 {3     // a23456 4     // 123456 5 }

This time when you are tracking the code, you will find that the G_STR address in the two compilation unit is not the same, because you modify it in one place, so the compiler is forcibly restored to the original memory, in memory there are two copies of the two modules in the use of variables. It is because of the above characteristics of static, so the general definition of static global variables, it is placed in the original file instead of the header file , so that the other modules will not cause unnecessary information pollution, the same thing to remember this principle!

extern and Const comparisons:

The const-decorated global constants in C + + have the same characteristics as static, that is, they can only be used in this compilation module, but a const may be used with an extern connection to declare that the constant can function in other compilation modules, such as extern const char g_str[];
Then in the original file do not forget the definition: const char g_str[] = "123456";

So when the const is used alone it is the same as static, and when working with extern, its characteristics are the same as extern! So for const I have nothing to describe too much, I just want to remind you that const char* G_STR = "123456" is different from the const char g_str[] = "123465" and the previous const modifier is char * instead of G_STR , its g_str is not constant, it is considered a defined global variable (can be used by other compilation units), so if you like to let char*g_str abide by the const global constants of the rules, it is best to define the const char* Const g_str= "123456 "。

[C + +] extern keyword explained and differs from static, const

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.