Header file definition of global variables and other issues (reproduced)

Source: Internet
Author: User

Can global variables be defined in header files that can be contained by multiple. c files? Why?

Yes. The global variables with the same name are declared in static form in different C files. Variables and functions cannot be directly defined in the header file, but static variables and classes can be defined.

Extern usage, global variables and header files (repeated definition)

# Include can contain declarations of variables and functions in other header files. Why do I need the extern keyword? If I want to reference a global variable or function, I only need to include # include <XXX. h> (XXX. h contains the statement of a.) Is that okay? Why use extern ?? This problem has always been a real problem that has plagued me for many years. Today, I checked the Internet and finally got a small profit:

Header file

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. Compile it into Lib, DLL, OBJ,. O, and so on. Then, 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 a description, the header file contains the "Declaration" of functions, variables, and classes. 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: # ifndef _ XX _ header file. h # DEFINE _ XX _ header file. h int A; # endif. Unfortunately, int A is defined as a global variable. If this header file is referenced multiple times, your A will be repeatedly defined. Obviously, the syntax is wrong. However, with this # ifndef Conditional compilation, you can ensure that your header file is referenced only once, but it may be wrong, 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 !!!


This keyword is really hateful. During the Declaration, this extern can be omitted, so you may not know whether it is declaration or definition. The following two types are divided into variables and functions:

(1) variables

Especially for variables. Extern int A; // declare 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; // define a global variable A and give the initial value. The fourth variable is equal to the third variable, which defines a global variable that can be used by the outside and gives 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 need to declare, extern int A; at this time, extern cannot be omitted, because if it is omitted, it becomes int A; this is a definition, not a declaration.

(2) Functions and declarations are also the same for functions. extern is used for definition, indicating that this function can be referenced externally, use extern to declare the statement. 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, so the extern can be omitted during function definition and description, other files also know that this function is defined elsewhere, so it can be done without the extern. The two are so different that extern is omitted. For example, int fun (void) {return 0;} is very good. We define a global function int fun (void); we declare it, then we can use the add-and-Remove-extern statement later. We can also put the declaration of fun in a header file, and finally it becomes int fun (void); // function declaration, therefore, extern is omitted. The complete values are extern int fun (void); 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, 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.


For a variable, if you want to use the variable of another source file in this source file, you need to declare the variable with extern before use, or declare the variable with extern in the header file;

For a function, if you want to use a function of another source file in this source file, you need to declare the variable before use. It does not matter if the declared function is added without the extern, therefore, you do not need to add extern to the function in the header file.

C Programs adopt Modular programming ideas. A large software should be reasonably divided into a series of functional independent parts to complete the system's requirements. The module division is mainly based on functions. The module consists of the header file and the implementation file. The correct method of using the header file and the implementation file is: Rule 1 header file (. h) is the declaration of the interface of this module. The interface includes the external functions and external global variables provided by this module to other modules. the file in H is declared with the extern keyword; the functions and global variables in Rule 2 must be in. the C file starts with a static keyword Declaration; rule 3 should never be in. variables are defined in the H file. Many programmers are ambiguous about defining variables and declaring variables. The difference between defining variables and declaring variables lies in the definition of Memory Allocation Operations, which is the concept of the assembly phase; the declaration only tells the module that contains the Declaration to find external functions and variables from other modules during the connection phase. For example, int A = 5; # include "module1.h" # include "module1.h" # include "module1.h" and above. The result is that the integer variable A is defined in Modules 1, 2, and 3, A corresponds to different address units in different modules, which obviously does not conform to the writer's intention. The correct method is: extern int A; # include "module1.h" int A = 5; # include "module1.h" # include "module1.h". In this way, if Module 1, 2, and 3 operate on a, it corresponds to the same memory unit.

Rule 4: If you want to use variables and functions defined by other modules, directly include the header file. Many programmers like this. When they want to access variables defined by other modules, they add the following statement at the beginning of the module File: extern int externvar; abandon this practice, as long as the header file is completed according to rule 1, when a module needs to access the global variables defined in other modules, it only needs to include the header file of this module.

The shared variable declaration is like sharing variables between functions. variables can be shared in files. To share a function, you need to put the function definition in a source file, and then place the Declaration in other files that need to call this function. The method for sharing variables is similar to this method. Before that, you do not need to distinguish the declaration of a variable from its definition. To declare variable I, it is written in the following form: int I; this not only declares that I is an int type variable, but also defines I, so that the compiler can leave space for I. To declare an unspecified variable I, You need to place the keyword extern: extern int I at the beginning of the variable Declaration; extern indicates that the compiler variable I is defined elsewhere in the Program (most of which may be in different source files), so no space needs to be allocated for I. By the way, extern can be used for all types of variables. When using extern in the array declaration, you can ignore the length of the array: extern int A [], because at this moment the compiler does not need to allocate space for Array, therefore, you do not need to know the length of array. To share variable I in several source files, first place the definition of variable I in a file: int I. If you need to initialize variable I, you can place the initial value here. When compiling this file, the compiler will allocate memory space for variable I, while other files will include the declaration of variable I: extern int I; by declaring variable I in each file, allows you to access/or modify variable I in these files. However, due to the keyword extern, the compiler does not allocate additional memory space for variable I each time a file is compiled. When a variable is shared in a file, it faces a challenge similar to the shared function: ensure that all declarations of the variable are consistent with the definition of the variable. To avoid conflicts, the shared variable declaration is usually placed in the header file. The source file that needs to access special variables can contain the appropriate header file later. In addition, the source file containing the variable definition contains each header file containing the variable declaration, so that the compiler can check whether the two match.

If the project is large, there are many header files, and several header files are frequently used, then 1. Write all these header files into a header file, such as preh. H 2. Write a preh. C with only one sentence: # include "preh. H" 3. For preh. C, set creat precompiled headers in project setting. For other C files, set use precompiled header file

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.