[Convert] the difference and connection between extern and header file (*. h)

Source: Internet
Author: User

# Include can contain the declaration of variables and functions in other header files. Why do we need the extern keyword?

If I want to reference a global variable or function a, I just need to include # include <XXX. h> (XXX. h contains the statement of a.) Is that okay? Why use extern ??

This problem has always plagued me for a long time. After practice and searching for information, it is summarized as follows:

I. header files

First, let's talk about the header file. In fact, the header file has no effect on the computer. She just expanded it at # include during pre-compilation, which makes no difference, in fact, the header file is mainly for others.

I did an experiment, changed the suffix of the header file to xxx.txt, and then used

# Include "xxx.txt"

Compilation and links have passed smoothly. We can see that the header file only serves to read the code and has no other functions!

Whether it's C or C ++, you put your functions, variables, struct, and classes in your. C or. cpp file. Then compile it into Lib, DLL, OBJ,. O, etc. When others use it, the most basic GCC hisfile. cpp Yourfile. o | OBJ | DLL | lib and so on.
But for our programmers, how do they know what is in your Lib, DLL? It depends on your header file. Your header file is a description of the user. Descriptions of functions, parameters, and various interfaces.
Since this is an illustration, the header file contains the "Declaration" of functions, variables, and classes (also called function prototypes. Remember, it is a "Declaration", not a "Definition ".

Then, let me assume that you know the differences between the Declaration and definition. Therefore, it is best not to define something in the header file. For example, global variables:
/* XX header file */
# Ifndef _ XX _ header file. h
# DEFINE _ XX _ header file. h
Int;
# Endif

In this case, int A is a global variable, so if this header file is referenced multiple times, your A will be repeatedly defined, apparently, the syntax is wrong. Only with this # ifndef Conditional compilation, you can ensure that your header file is referenced only once, but it may not happen, however, if multiple C files contain this header file, errors will still occur, because the macro name is only valid for the current C source file, so there will be no errors during compilation of these multiple C files, however, an error will be reported during the link, 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

Note !!!

Ii. extern

This keyword is really hateful. when defining a variable, this extern can be omitted (by default, it is omitted); When declaring a variable, this extern must be added before the variable, so sometimes you may not know whether to declare or define it. In other words, the declaration is not necessarily the extern before the variable, but the definition can only be used if the extern is not before the variable. Note: It is defined to allocate memory space for the variable, but it is declared that no memory space needs to be allocated for the variable.

The following are two types of variables and functions:

(1) variables

Especially for variables.
Extern int A; // declare a global variable
Int A; // defines a global variable.

Extern int A = 0; // define a global variable A and give the initial value.
Int A = 0; // defines a global variable A and returns the initial value,

The fourth is equal to the third, which defines a global variable that can be used externally and returns the initial value.
Confused, they look really like. But the definition can only appear in one place. That is to say, either int A; extern int A = 0; or int A = 0; can only appear once, and that extern int A can appear many times.

When you want to reference a global variable, you must declare extern int A. At this time, extern cannot be omitted, because it becomes int A. This is a definition, not declaration. Note: extern int A; Type int can be omitted, that is, extern A; but other types cannot be omitted.

(2) Functions
The same is true for a function. It is also a definition and Declaration. When it is defined, extern indicates that this function can be referenced by external entities. When it is declared, extern indicates that this is a declaration. However, because the definition of a function is different from that of a declaration, the definition function must have a function body, and the declaration function does not have a function body (and it must end with a semicolon ), therefore, you can omit extern in the function definition and description. Other files also know that this function is defined elsewhere, so it is fine without the extern. The two are so different that extern is omitted.
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 on it, and then we can use it later.
The addition of extern is the same.
We can also put the statement of fun in a header file, and finally it becomes like this
/* Fun. H */
Int fun (void); // function declaration, so extern is omitted. The complete values are extern int fun (void );
/* Corresponding fun. cpp file */
Int fun (void)
{
Return 0;
} // A complete global function definition. Because of the function body, extern is also omitted.
Then, a customer, a customer who wants to use your fun, will include this header file, OK, and a global declaration. No problem.
However, if the customer wants to use a global variable, the extern variable must be used. Otherwise, the definition is defined.

Summary:

For variables, if you want to use another source file (such as file name B) in this source file (such as file name A), there are two methods: (1) in File A, you must use extern to declare the variables defined in file B (of course, global variables). (2) Add the header file corresponding to file B to file, of course, this header file contains the variable declaration in file B, that is, the variable must be declared with extern in this header file. Otherwise, the variable is defined again.

For a function, if you want to use a function of another source file (such as file name B) in this source file (such as file name A), there are two methods: (1) use extern in file a to declare the functions defined in file B (in fact, you can also omit extern. You only need to see the prototype of the function defined in file B in file a). (2) add the header file corresponding to file B to file a. Of course, this header file contains the function prototype in file B. in the header file, the function does not need to add extern.

**************************************** **************************************** **************************************** ******************************

There is another saying for the above summary:

(A) call the global variables of another file in one file, because the global variables are generally defined in the original file. in C, we cannot use # include to include the source file but only the header file. Therefore, the common method is to use extern int A to declare external variables. Another method is. the global variable int global_num is defined in the C file. write extern int global_num in the H header file, so that other source files can use include. h To declare that she is an external variable.

(B) Examples of variables and functions

Int fun (); and extern int fun (); are declarations (definitions must have an implementation body ). Use extern int fun () to specify whether it is a declaration.

And int A; is the definition

Extern int A; is a declaration.

(3) In addition, the extern modifier can be used to call C functions in C ++ programs.

For example, to call a C-Database Function in C ++, you must declare the function to be referenced using extern "C" in C ++. This is for the linker and tells the linker to use the c Function Specification for link. The main reason is that C ++ and C programs have different naming rules in the target code after compilation.

During compilation, the C ++ language will combine the names and parameters to generate an intermediate name to solve the polymorphism problem, but the C language will not, therefore, the corresponding link cannot be found. In this case, C needs to use extern "C" to specify the link. This tells the compiler to keep my name, do not generate an intermediate name for the link for me.

3. Connection Between extern and header files
This kind of connection also solves the first two problems:

(A) Use # include to include the declaration of variables and functions in other header files. Why do I need the extern keyword?

(B) if I want to reference a global variable or function a, I just need to include # include <XXX. h> (XXX. h contains the statement of a.) Is that okay? Why use extern ??

Answer: if a file (assuming file name a) needs to reference a large number of variables or functions defined in another file (assuming file name B), the header file is more efficient and the program structure is more standard. For other files (such as file name c and d) to reference the variables or functions defined in file name B, you only need to use # include to include the header file corresponding to file B (of course, this header file only declares variables or functions and cannot be defined.

**************************************** **************************************** **************************************** ********************

At that time, the compiler only knew the. C (or. cpp) file, but did not know what. h was.
At that time, people wrote a lot. C (or. CPP) files, gradually, people found in many. C (or. CPP) the declared variables or function prototype in the file are the same, but they have to repeat the content into each word. C (or. CPP) file. But what's even more frightening is that when one of the statements changes, you need to check all the. C (or. cpp) files and modify the statements in them ~, It's the end of the world!
Finally, some people (maybe some people) can no longer endure this kind of torture. They extract the repeated parts and put them in a new file. C (or. CPP. In this way, even if a declaration has changed, you do not need to look for and modify it everywhere-the world is so beautiful!
Because this new file is often placed in the header of the. C (or. cpp) file, it is called the "header file" with the extension. h.
From then on, the compiler (in fact, The Preprocessor) will know that in addition to the. C (or. cpp) file, there will be a. h file, and a # include command.

 

From: Link

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.