Const, static, extern usage summary, constextern

Source: Internet
Author: User

Const, static, extern usage summary, constextern

Const application:

1. For the basic declaration const int r = 100; // standard const variable declaration and initialization, the compiler will directly replace it with 100 during compilation after the type check.

2. For pointer 1. int x = 10; const int * r = & x; // The Pointer Points to a constant. The content pointed to by r cannot be changed through r, but if it is not const, the content can be changed by yourself, and the r pointer can be changed. It can point to other shaping types.

// * R = * r + 1; NO // x ++; YES // r = & y; YES

2. int const * r = & x; identical to 1

3. int * const r = & x; // The Pointer Points to a constant and cannot be modified to point to other content.

// R = & y; NO // * r = * r + 1; YES // x ++; YES

4. const int * const r = & x; // in combination with 1 and 3 usage, r is a constant pointer to a constant. The pointer cannot be changed, and the pointer content cannot be changed, content can be changed by itself

// R = & y; NO // * r = * r + 1; NO // x ++; YES

3. You can assign a non-const object to the const pointer for the type check, so that it cannot be changed. however, you cannot assign a const to a non-const unless you first forcibly convert the const int x = 100; int * p = (int *) & x; * p ++;

Iv. Functions

1. void Fuction1 (const int r); // The const value is passed for the parameter, meaning that the initial value of the variable cannot be changed by the function.

2. const int Fuction1 (int); // The returned const value indicates that the initial value of the variable in the returned original function cannot be modified, but the variable returned by the function by value is copied, it makes no sense if it can be modified. It can be assigned to any const or non-const type variable without the need to add this const keyword.

3. Class CX; // there is an internal constructor, such as CX (int r = 0)

CX Fuction1 ()

{Return CX ();} // create a temporary variable outside the function for return, instead of being created inside the function, and then copy it to the temporary variable outside the function.

Const CX Fuction2 ()

{

Return CX ();

}

Fuction1 () = CX (1); // No problem. It can be called as the left value.

Fuction2 () = CX (1); // compilation error. The return value of const cannot be called as the left value. // Function1 and Function2 return external temporary variables. The temporary variables returned by Function2 are of the const type and cannot be repaired.

// Modify. Once the statement is executed, the temporary variable is automatically destroyed.

 

4. Pass and return the const of the pointer in the function:

Int F1 (const char * pstr ); // when being passed, you can use the const modifier to ensure that the initial value of the passed parameter is not modified using this pointer. // The content pointed to by pstr cannot be modified, pstr [0] cannot be modified, for example:


Int Test (const char * pCh)
{
// PCh [3] = 'D'; const modified the compilation.
Return 1;
}

 

Const char * F2 (); // indicates that the pointer returned by the function points to a const object, it must be assigned a pointer to the const object. // Since the returned value is const char *, the returned value is a string that cannot be modified, therefore, you must assign a pointer to the const object.

Const char * const F3 (); // a const is used more than the preceding one. This const is valid only when it is used as the left value, it indicates that this pointer cannot be modified in addition to pointing to a const object, so it cannot be processed as a left value. // The preceding const int * const r = & x; is similar

 

5. For Category 1. first, the const member variables can only be initialized in the const using the initialization member list. If you try to initialize the const member variables in the const body, a compilation error will occur.

Initialize the member list, for example, X: X (int ir): r (ir) {}// assume that r is a const member variable of class X.

Note: neither class const nor destructor can be const functions.

2. a const member function is created, but you still want to use this function to change the data in the object. (The function cannot modify the data member of the class)

// Assume there is a class named X, which has an int member variable r. We need to perform ++ r operations on this r through a const member function f,

The Code is as follows:

Void X: f () const {(const_cast (this)-> ++ r ;}// implement forced type conversion using the this pointer

 

--------------------------- STATIC ----------------------------

Distribution in memory of a complete program:

===========| Code area |

------------------ | Global data zone |

------------------ | Heap area |

----------------- | Stack area |

 

In general, dynamic data generated by new is stored in the heap zone, automatic variables in the function are stored in the stack zone, and global variables and static variables are stored in the global data zone.

Static has the following functions: 1. Extended survival; 2. restricted scope; 3. uniqueness

STATIC:

1. for static 1 and [static global variables] In process-oriented design, // Add the keyword static before the global variable, which is defined as a static global variable.

Static global variables have the following features:

1) The variable allocates memory in the global data zone;

2) The uninitialized static global variable will be automatically initialized to 0 by the program (the value of the automatic variable is random unless it is explicitly initialized );

3) Static global variables are visible in the entire declared file, while extern outside the file is invisible;

 

You can share variables in files by defining global variables, but defining static global variables has the following benefits:

1) Static global variables cannot be used by other files;

2) variables with the same name can be defined in other files without conflict;

2. [static local variable] Add the keyword static before the local variable, which is defined as a static local variable.

 

Generally, a variable is defined in the function body, and stack memory is allocated to the local variable whenever the program runs the statement. However, as the program exits from the function body, the system will reclaim the stack memory and the local variables will also become invalid. But sometimes we need to save the variable value between two calls. The general idea is to define a global variable for implementation. In this way, the variable no longer belongs to the function itself, and is no longer only controlled by the function, causing inconvenience to program maintenance. Static local variables can solve this problem. Static local variables are stored in the global data zone, instead of in the stack. Each value is kept to the next call until the next value is assigned.

 

Static local variables have the following features:

1) The variable allocates memory in the global data zone;

2) Static local variables are initialized for the first time when the program executes the declaration of the object, that is, subsequent function calls will not be initialized;

3) Static local variables are generally initialized at the Declaration. If no Explicit initialization is performed, the program will automatically initialize the variable to 0; // It indicates that the initial initialization at the declaration is not performed at the definition, static data is allocated with memory at the time of compilation.

4) It always resides in the global data zone until the program is running. However, its scope is local scope. When its function or statement block is defined to end, its usage domain ends;

 

3. A static function is defined as a static function by adding the static keyword before the return type of the function. A static function is different from a common function. It can only be seen in the file where it is declared and cannot be used by other files.

Benefits of defining static functions:

1) static functions cannot be used by other files;

2) functions with the same name can be defined in other files without conflict;

 

2. Object-oriented static keywords (static keywords in the class)

1. A static data member adds the keyword static before the declaration of the data member in the class. This data member is a static data member in the class.

Static data members have the following features:

1) static data members are treated as class members. No matter how many objects are defined for this class, the static data member has only one copy in the program, which is shared by all objects of this type.

2) static data members are stored in the global data zone and all objects in this category are shared. Therefore, they do not belong to a specific class object and are visible in the scope when no class object is generated, that is, when no class is generated, we can operate on it. Compared with global variables, using static data members has two advantages:

1) The static data member does not enter the global namespace of the program, so there is no possibility of conflict with other global names in the program;

2) [hide information]. Static data members can be private members, but global variables cannot;

 

2. static member functions serve all the services of a class, rather than the specific objects of a class. Compared with normal functions, static member functions do not have the this pointer because they are not associated with any objects. In this sense, it cannot access non-static data members of class objects or non-static member functions. It can only call other static member functions. Static member functions can be summarized as follows:

1) The keyword static cannot be specified for function definitions that appear in the class in vitro;

2) Static members can access each other, including static member functions accessing static data members and accessing static member functions;

3) non-static member functions can access static member functions and static data members at will;

4) static member functions cannot access non-static member functions and non-static data members.

 

----------------------------------- EXTERN ----------------------------

The basic interpretation of EXTERN 1 can be placed before a variable or function to indicate that the definition of a variable or function is in another file, prompting the compiler to find its definition in other modules when it encounters this variable and function. Through this behavior, it tells the compiler that the definition of the variable/function already exists somewhere and allows the compiler to look for its definition in other modules. In addition, extern can be used to specify links.

2. extern "C" uses extern "C" mainly because the C ++ language implements polymorphism during compilation, function names and functions are combined to form another function name (in short, the compiled function name is different from the one you previously declared ), the concept of no polymorphism in C Language certainly does not have this strange name change problem. This is the problem. When you want to call the C function in C ++, because of the different names, it will not find the definition of the called function, therefore, an error occurs. In order to solve the conflicts between C and C ++, extern "C' exoccurs '.

 

The first scenario -- extern

In the Bock's announcement, I saw a good sentence and reprinted it together:If you have an apple and I have an apple, we will exchange it with one person, but if you have an idea, I will exchange it with you, each person has two ideas.

The extern keyword declares that the variable and function are external links, that is, the variable or function name is visible in other files. Variables or functions declared with them should be defined in another file or elsewhere in the same file.

For example, the statement: extern int a; is just a declaration of a variable. It does not define variable a and does not allocate memory space for variable. Variable a can only be defined once as a global variable in all modules. Otherwise, a connection error occurs. In general, the function and global variables referenced by this module to other modules are declared with the keyword extern in the module header file. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module. In this way, when Module B calls A function in module A, although Module B cannot find the function in the compilation phase, no error is reported; it will find this function from the target code generated by module A during the connection phase. If a project contains the following two files: 1. cppAs follows: 2. cppInt x, y; extern int x, y; extern void PrintHello (); void PrintHello () void Func1 () {cout <"hello! "<Endl; x = 123 ;}} void Func2 () int main () {y = x * 10; PrintHello ();}......}

In 2. cpp uses extern int x, y; only declares the two variables x and y. It tells the compiler that the variables after it are described in other files and no memory is allocated to them. When both files are compiled into. obj, all external variables and functions are unified during the connection, and global variables and functions defined by each file can be shared. //This example is very good and easy to understand.

 

Address: http://www.cnblogs.com/crhacker/archive/2006/06/09/421669.html

Scenario 2 -- extern "C"

(Conversion) in-depth exploration of the meaning of extern "C" in C ++ 1. Introduction

C ++ language was originally created as "a better C ", however, this does not mean that the compilation and connection methods used by global variables and functions similar to C in C ++ are the same as those in C. As a language to be compatible with C, C ++ retains the features of some procedural languages (known as "not completely oriented objects "), therefore, it can define global variables and functions that do not belong to any class. However, C ++ is an object-oriented programming language after all. To support function overloading, C ++ treats global functions differently from C. 2. Start with the standard header file

An enterprise once gave the following interview questions:

Why are the standard header files having the following structures?

 

# Ifndef _ INCvxWorksh

# Define _ INCvxWorksh

# Ifdef _ cplusplus

Extern "C" {# endif/*... */# ifdef _ cplusplus}

# Endif

# Endif

/* _ INCvxWorksh */

Obviously, the compilation macro "# ifndef _ INCvxWorksh, # define _ INCvxWorksh, and # endif" in the header file is used to prevent the header file from being repeatedly referenced.

So

# Ifdef _ cplusplus extern "C" {# endif # ifdef _ cplusplus} # endif

What is the role? We will discuss it one by one below. 3. Deep encryption extern "C"

Extern "C" contains a double meaning, which can be obtained literally: first, the target is "extern", and second, the target is "C. Let's explain these two meanings in detail.

The function or variable specified by extern "C" is of the extern type;

Extern is a keyword in C/C ++ that indicates the range (visibility) of functions and global variables. This keyword tells the compiler, the declared functions and variables can be used in this module or other modules. Remember, the following statements:

Extern int;

It is just a declaration of a variable. It does not define variable a and does not allocate memory space for variable. Variable a can only be defined once as a global variable in all modules. Otherwise, a connection error occurs.

In general, the function and global variables referenced by this module to other modules are declared with the keyword extern in the module header file. For example, if Module B wants to reference the global variables and functions defined in module A, it only needs to include the header file of module. In this way, when Module B calls A function in module A, although Module B cannot find the function in the compilation phase, no error is reported; it will find this function from the target Code Compiled by module A in the connection phase.

The keyword corresponding to extern is static. The global variables and functions modified by it can only be used in this module. Therefore, a function or variable can only be used by this module and cannot be modified by extern "C.

Variables and functions modified by extern "C" are compiled and connected in C language;

Compilation Method without the extern "C" declaration

First, let's take a look at how C-like functions are compiled in C ++.

As an object-oriented language, C ++ supports function overloading, while Procedural Language C does not. The name of the function in the symbol library after being compiled by C ++ is different from that in the C language. For example, assume that the prototype of a function is:

Void foo (int x, int y );

After the function is compiled by the C compiler, its name in the symbol library is _ foo, while the C ++ compiler generates names such as _ foo_int_int (different compilers may generate different names, but all adopt the same mechanism, and the new name is called "mangled name ").

A name such as _ foo_int_int contains the function name, number of function parameters, and type information. C ++ relies on this mechanism to implement function overloading. For example, in C ++, the void foo (int x, int y) and void foo (int x, float y) functions generate different symbols, the latter is _ foo_int_float. Similarly, variables in C ++ support both local variables and class member variables and global variables. The class member variables of the program written by the user may have the same name as the global variables, which are distinguished. In essence, when the compiler is compiling, it is similar to the function processing, and it also takes a unique name for the variables in the class, this name is different from the global variable name with the same name in the user program.

Connection method when extern "C" is not added

Suppose in C ++, the header file of module A is as follows:

// Module A header file moduleA. h

# Ifndef MODULE_A_H

# Define MODULE_A_H

Int foo (int x, int y );

# Endif

Reference this function in Module B:

// Module B implements the file moduleB. cpp

# Include "moduleA. h"

Foo (2, 3 );

In fact, in the connection phase, the connector looks for symbols such as _ foo_int_int from the target file moduleA. obj generated by module!

Compilation and Connection Methods After the extern "C" clause is added

After the extern "C" statement is added, the header file of module A is changed:

// Module A header file moduleA. h # ifndef MODULE_A_H # define MODULE_A_H extern "C" int foo (int x, int y); # endif

In Module B's implementation file, foo (2, 3) is still called. The result is:

(1) When module A compiles and generates the foo target code, it does not perform special processing on its name and uses the C language;

(2) When the connector looks for the foo (2, 3) call for the target code of Module B, it looks for the unmodified symbol name _ foo.

If the function in module A declares that foo is of the extern "C" type, and Module B contains the extern int foo (int x, int y ), module B cannot find the function in module A, and vice versa.

//Because of the mismatch, extern int foo (int x, int y) is compiled in C ++ mode.

 

  Therefore, we can summarize the true purpose of the statement "extern" C "in one sentence.(The birth of any syntactic feature in any language is not random and comes from the needs of the real world. When thinking about a problem, we should not just focus on how the language is made, but also ask why it is doing so and what the motivation is, so that we can better understand many problems ):

 Realize mixed programming of C ++, C and other languages.  

Understand the motivation for setting up extern "C" in C ++. Next we will analyze the common usage skills of extern "C.

 

4.Usage of extern "C"

(1) To reference functions and variables in C language in C ++, the following processing must be performed when the C Language header file (assumed as cExample. h) is included:

Extern "C" {# include "cExample. h "}

  In the header file of the C language, the external function can only be specified as the extern type. The C language does not support the extern "C" declaration. when the c file contains extern "C", a compilation syntax error occurs.

The source code of the three files in the example project of C ++ referenced by the author is as follows:

/* C header file: cExample. h */

# Ifndef C_EXAMPLE_H

# Define C_EXAMPLE_H

Extern int add (int x, int y );

# Endif

 

/* C language implementation file: cExample. c */

# Include "cExample. h"

Int add (int x, int y)

{Return x + y ;}

 

// C ++ implementation file, call add: cppFile. cpp

Extern "C" {# include "cExample. h "}

Int main (int argc, char * argv [])

{

Add (2, 3 );

Return 0;

}

  If C ++ calls a. DLL written in C language, when it includes the header file of. DLL or the declared interface function, it should add extern "C "{}.

(2) When referencing functions and variables in C ++ in C, the header file of C ++ needs to add extern "C ", however, you cannot directly reference this header file that declares extern "C" in C. You should only declare the extern "C" function defined in C ++ as the extern type. The source code of the three files contained in the example project of C ++ is as follows:

// C ++ header file cppExample. h

# Ifndef CPP_EXAMPLE_H

# Define CPP_EXAMPLE_H

Extern "C" int add (int x, int y );

# Endif/

/C ++ implementation file cppExample. cpp

# Include "cppExample. h"

Int add (int x, int y)

{

Return x + y;

}

/* C implementation file cFile. c /*

This will cause compilation errors: # include "cExample. h "*/

Extern int add (int x, int y );

Int main (int argc, char * argv [])

{

Add (2, 3 );

Return 0;

}

If you thoroughly understand the role of extern "C" described in section 3rd in the compilation and connection phases, you can really understand the usage of referencing C Functions and C ++ functions from C ++ described in this section. Pay special attention to the sample code given in section 4th.

Address: http://www.cppblog.com/Macaulish/archive/2008/06/17/53689.html

Adding some experiences

When the function of the dynamic link library is called using the "dynamic reflection" method,

Eg:

Typedef StubBase * (* func )();

Func fun = (func) GetProcAddress (dllhandle, LPCSTR ("methodName "));

In order to make this dynamic reflection successful, it is best to use extern "C" in the dll implementation code to modify it. As follows:

Extern "C" {_ declspec (dllexport) StubBase * methodName () {StubBase * x = new StubBase (); return x ;}}

This ensures that the compiler compiles function names in the same way when the dynamic reflection function address is used, and all functions are compiled in the C language format.

 

Note: The above content is all reprinted and dynamic reflection. I don't understand the function part that calls the dynamic link library. The content in other red parts is better, I have a little bit of experience!

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.