This article turns from: http: // lpy999.blog.163.com/blog/static/117372061201182051413310/http://blog.csdn.net/ feitianxuxue/article/details/7204116 Thank bloggers, if there is infringement please notify the deletion
With # include to include the declarations of variables and functions in other header files, why do I need the extern keyword?
If I want to refer to a global variable or function A, I just have to include #include<xxx.h> (xxx.h contains a declaration) directly in the source file, why use extern??
This question has been a paradox for a long time, after the practice and find information, the following summary:
First, the header file
First of all, the head file, in fact, the first file on the computer does not work, she just in the pre-compilation in # # # place, no other meaning, in fact, the head file is mainly for others to see.
I did an experiment by changing the suffix of the header file to Xxx.txt, and then using the header file where it was referenced.
#include "Xxx.txt"
Compile, links are very smooth past, so, the first file only for reading code role, no other role!
Whether it's C or C + +, you put your functions, variables, or structs, classes, or whatever, in your. C or. cpp file. Then compile into lib,dll,obj,.o and so on, then others use the time, the most basic gcc hisfile.cpp yourfile.o|obj|dll|lib and so on.
But for our programmers, how do they know your lib,dll ... What the hell is going on inside? To see your head file. Your header file is a description of the user. Functions, parameters, descriptions of various interfaces.
If that is the case, then the nature of the first file is about functions, variables, and "Declarations" of classes (also called function Prototypes for functions). Remember, it is "declaration", not "definition".
The difference between declaration and definition.
There are two scenarios for declaring a variable:1, one is the need to create storage space. For example:intA storage space has been established at the time of declaration. 2, and the other is that there is no need to create storage space. For example:extern intA where variable A is defined in another file. A declaration is a name-identifier that is introduced to the compiler. It tells the compiler "This function or variable can be found somewhere, what it looks like". The definition is, "create a variable here" or "Create a function here". It allocates storage space for the name. Whether you define a function or a variable, the compiler allocates storage space for them at the defining point. For variables, the compiler determines the size of the variable, then opens up space in memory to hold its data, and for functions, the compiler generates code that eventually consumes a certain amount of memory. All in all: make the declaration of building space a "definition" and make it a "declaration" that does not need to create storage space. The Declaration and definition (initialization) of a basic type variable is generated at the same time, whereas for an object, the declaration and definition are separate. For example, if a is a; A, it is a declaration that tells the compiler that a is an object variable of Class A, but does not initialize;=Newa (); This is initialization, allocating space. (The ultimate purpose of our statement is to use it in advance, that is, before it is defined, if it is not necessary to declare it separately if it is not required to be used in advance, so is the function, so the declaration does not allocate storage space, and the storage space is allocated only when defined.) The function of declaring a variable with static is two: (1for a local variable with a static declaration, the space allocated for the variable is always present throughout the execution period of the program. (2if the external variable is declared with static, the function of the variable is limited to this file module. Supplement: What is definition? What is a statement? What is the difference between them? The so-called definition is (the compiler) creates an object, allocates a piece of memory for the object, and gives it a name, which is what we often call variable names or object names. The declaration has a 2-heavy meaning: (1tells the compiler that the name has been matched to a piece of memory, and the following code uses a variable or object that is defined somewhere else. A declaration can occur more than once. (2tell the compiler that the name is already reserved, and that it can no longer be used as a variable name or object name elsewhere. The most important difference between definition and declaration is that the definition creates an object and allocates memory for the object, declaring that no memory is allocated.
So it's best not to be silly about defining something in the header file. such as global variables:
/*XX Header File */
#ifndef _xx_ header file. H
#define _XX_ header file. H
int A;
#endif
So, unfortunately, the int a here is the definition of a global variable, so if the header file is referenced multiple times, your A will be duplicated, obviously syntactically wrong. Just have this #ifndef conditional compilation, so can ensure that your header file is only quoted once, but may still not go wrong, but if more than one C file contains this header file will still error, because the macro name valid range is limited to the C source file, so in the compilation of the C file is not an error , but you will get an error when linking , saying that you have defined the same variable in multiple places,
Linking ...
Incl2.obj:error LNK2005: "int glb" ([email protected]@3ha) already defined in Incl1.obj
Debug/incl.exe:fatal error Lnk1169:one or more multiply defined symbols found
Attention!!!
Second, extern
This keyword is really hateful, when defining variables , this extern can actually be omitted (when defined, the default is omitted); when declaring a variable , the extern must be added before the variable, So sometimes it makes you wonder whether it's a statement or a definition. Or, the variable before the extern is not necessarily the declaration, and the variable before the extern can only be defined. Note: You define that you want to allocate memory space for a variable, while declaring that you do not need to allocate memory space for the variable.
There are two types of variables and functions:
(1) Variables
Especially for variables.
extern int a;//declares a global variable a
int A; Define a global variable a
extern int a = 0;//define a global variable A and give the initial value.
int a =0;//defines a global variable A, and gives the initial value,
The fourth is equal to the third one, which defines a global variable that can be used externally and gives the initial value.
I'm confused, they look like they are. But the definition can only appear in one place. That is, either int a or extern int a=0, or int a=0, which can occur only once, and that extern int a may appear many times.
When you want to reference a global variable, you have to declare that extern int A; At this time extern cannot be omitted, because omitted, it becomes int A; this is a definition, not a declaration. Note: extern int A; type int can be omitted, i.e. extern A; but other types cannot be omitted.
The
(2) Function
function, as well as the function, is also defined and declared, defined with extern, indicating that the function can be externally referenced, When declaring, use extern to indicate that this is a statement. However, since the definition and declaration of a function is different, the definition function has a function body, the declaration function does not have the function body (also has the end of the semicolon), so The function definition and declaration can be omitted out of , Anyway other files also know that this function is defined elsewhere, so do not add extern also line. The two are so different, so omitting the extern is not a problem.
For example:
/* A CPP file */
int fun (void)
{
return 0;
Well, we have defined a global function
/* Another CPP file */
int fun (void);
We made a statement to it, and then we can use the
Add no extern all the same
we can also put the statement of fun in a header file, and finally become such a
/*fun.h*/
int Fun (void); //function declaration, so the extern is omitted, complete is the extern int fun (void);
/* The corresponding fun.cpp file */
int fun (void)
{
return 0;
}//a complete global function definition, because there is a function body, extern is also omitted.
Then, a customer, a customer who wants to use your fun, includes this header file, OK, a global declaration. No problem.
However, if the client wants to use a global variable, then the extern variable is used, otherwise it is defined.
Summarize:
For a variable , if you want to use another source file (for example, file name a) in an original file (such as file name B), there are 2 ways: (1) The variable defined in the B file must be declared with extern in a file (the global variable, of course); (2) In a file to add the corresponding header file B file, of course, this header file contains the variable declaration in the B file, that is, in the head file must be declared with extern, otherwise, the variable is defined once.
For a function , if you want to use a function of another source file (such as file name B) in an original file (such as file name a), there are 2 ways: (1) The function defined in file B is declared in a file with extern (in fact, it can also omit extern, Just the B file definition function prototype can be in a file, and (2) Add the header file of B file in a file, of course, this file contains the function prototype in B file, in the header file function can not add extern.
*************************************************************************************************************** ***************************************
In the above summary in a different way of saying:
(a) for a global variable that invokes another file in one file, because the global variable is generally defined in the original file. C, we cannot include the source file with # # and can only contain header files, so the usual method is to declare an external variable with extern int A. Another way is to define the global variable int global_num in the a.c file, and you can write the extern int global_num in the corresponding A.H header file so that other source files can be declared by the include a.h that she is an external variable.
(b) There are different examples of variables and functions
int fun (); and extern int fun (); is a declaration (defined to have an implementation body). Using the extern int fun () is only a more explicit indication of the declaration.
and int A; is defined
extern int A; is a statement.
(3) In addition, the extern modifier can be used in C + + programs to invoke the canonical problem of C functions.
For example, invoking C library functions in C + + requires that the function to be referenced is declared in the C + + program with extern "C". This is for the linker, telling the linker to link with the C function specification when linking. The main reason is that C + + and C programs have different naming rules in the target code after compilation is complete.
The C + + language is compiled in order to solve The problem of polymorphism, the name and parameters will be combined to generate an intermediate name, and the language will not Therefore, the link can not find the corresponding case, C will need to use the extern "C" for the link designation, which tells the compiler, please keep my name, do not give me to generate the middle name for the link .
Iii. links to extern and header documents
This linkage also addresses the 2 questions that were originally raised:
(a) If you can include declarations of variables and functions in other header files with # include, why do I have the extern keyword?
(b) If I want to refer to a global variable or function A, I just have to include #include<xxx.h> directly in the source file (xxx.h contains a declaration), why use extern??
Answer: If a file (assuming file name a) is heavily referencing a variable or function defined in another file (assuming file name B), then using the header file is more efficient and the program structure is more prescriptive. Other files (such as file names C, D, etc.) to refer to variables or functions defined in file name B, simply include the header file corresponding to file B (the header file must not be defined for the declaration of a variable or function, of course).
*************************************************************************************************************** *****************************
It was a forgotten age, when the compiler knew only. C (or. cpp) files without knowing. h is the age of what.
At that time, people wrote a lot of. C (or. cpp) files, and gradually, people found that in many. c (or. cpp) files The declaration variables or function prototypes are the same, but they have to use a word and a word to repeatedly knock the contents into each. c (or. cpp) file. But even more frightening is that when one of the declarations changes, you need to check all the. C (or. cpp) files and modify the declarations in them, oh, it's the end of the world!
Finally, someone (perhaps some people) can no longer endure such torture, he or she extracts the repeating part, puts it in a new file, and then, in the desired. C (or. cpp) file, typing a statement such as # include XXXX. So even if a statement has changed, it is no longer necessary to find and modify the---the world is still so beautiful!
Because this new file is often placed on the head of A. C (or. cpp) file, it is named "header file" and the extension is. h.
From then on, the compiler (which is actually the preprocessor) knows that in addition to the. C (or. cpp) file, there is a. h file, and a command called # include.
Definitions and declarations, header files and extern summary (RPM)