The Application of C header files mainly involves the definition and declaration of global variables.

Source: Internet
Author: User
Recently, I encountered a small problem in my work. The application of C header files mainly involves the definition and declaration of global variables.
I have been studying the C language for several years, and I have been using it for nearly half a year. But I have not thought deeply about this part. the concept is vague, but the previous use is mostly relatively simple and does not involve complicated projects. Therefore, the definition and declaration are simple and clear. however, the recent major project has made me suffer a little bit in this regard. Although I can quickly correct other people's code, I do not know the reasons behind these corrections. I think most programmers who like C language should be the same as me. They always like to investigate the underlying causes behind program problems. This is exactly the most fundamental reason why I like C language.
After reading an article by Janders in csdn today, I have learned a lot more about it and I have learned a little bit about it.
I have reproduced the article, corrected some spelling mistakes in the article, and made some modifications to the text and layout. C language. I have known hpost for a long time. Although its usage is not very complex, I have been using it for several months, only in a few years have we gradually understood his true colors. For some reason, it is certainly one of the reasons that I have been blunt and hard to learn, but there are other reasons. Cause 1: it is difficult to fully develop the role of a small project. In other words, even if you do not know how to use the project, the program will run on the computer. Cause 2: The current C language books only detail the syntax of the C language, but do not mention the file organization structure of the entire program, I found several well-known C language books, but none of them. the usage of the H file is quite thorough. Next, I will give a brave speech and introduce it to you based on my understanding of. h. Let our thoughts go back to the first year of college on a time machine. C. Our first C Language Program: Hello world! File name first. cmain () {printf ("Hello World !");} Routine-1 look at the above program, there is no. h file. Yes, that is, none. Everything in the world has gone through a process that has never been found. We have a certain understanding of. h. I think we also need to start from this step. At this time, we do not need a. h file, because this program is too simple to need. So how can we make it necessary? Let's make this program a little more complex. Please refer to the following file name: first. cprintstr () {printf ("Hello World !");} The main () {printstr ()} routine-2 still does not exist, so let's make a slight change to this program. file name first. cmain () {printstr ()} printstr () {printf ("Hello world! ");} Routines-3 and so on, not just changing the order, but the results are quite different. let's compile the routines-2 and routines-3. You will find that the routines-3 are not compiled. in this case, we need to understand another concept in C language: scope. here we will only talk about. the top-level scope related to hware. The top-level scope is extended from the declaration point to the end of the source program text. For the printstr () function, there is no separate declaration, only definition, from the defined row to the first. the C file ends, that is, it is already in its scope at the reference point of the main () function in routine-2. the reference point of the main () function in routine-3 is not in its scope, so compilation will fail. what should we do in this situation? There are two methods. One is to let us go back to the routine-2. The order is nothing for us. Who should be the first and then? As long as the program can be compiled and run, let's keep the main () file at the end. let's look at another routine. Let's see if this method works at any time. file name first. c
Play2 ()
{................... Play1 ();.................... }
Play1 (){
................. Play2 ();
........................
} Main () {play1 ();} most of the routines-4 may be seen. This is a frequently used algorithm and nested function. Let's take a look, which of the following functions is play1 and play2 in front? In this case, we need to use the second method, using the Declaration. File name first. cplay1 (); play2 (); play2 (){................... Play1 ();....................
}
Play1 ()
{
......................... Play2 ();........................
} Main () {play1 ();} routines-4 have been nagging me for a long time. With the help of the four routines, we finally started the qualitative change caused by quantitative changes, the topic of this article. the H file is about to appear. A large software project may have thousands or tens of thousands of plays, not just play1 and play2, so there may be n play1 (); play2 (); in this statement, we need to find a way to manage play1 (); play2 (), instead of putting it in. c file, so. the H file appears. file name first. hplay1 (); play2 (); file name first. C # include "first. h "play2 (){................... Play1 ();....................}
Play1 ();{.......................... Play2 ();........................} Main () {play1 ();} routine-4 you may say that the Janders prawn is too cool. I know the above. You have been talking about it for so long, please forgive me. if 80% of the people above know the content, I promise that 80% of the people below do not know it completely. this is also my consistent style of describing one thing. I always want to clarify one thing so that people who have just come into contact with C can understand it. above is. the most basic functions of the H file. what other functions does the H file have? Let me describe a project on hand. this project has been in operation for more than 10 years. In actual years, no one in our department can say it is inaccurate. Besides, the time is not the most important and we will not go into details. It is the front-end software of a communication device. The source file size is 51.6 MB, the size is 1601 files, and the size is about 10 MB after compilation. It can be imagined that there is a complicated call relationship here, for example, in second. there is another function in C that needs to call first. how to Implement the play1 function in the C file? Sencond. h file play1 (); sencond. c file ***(){................ Play ();...................} Routine-5 declares the play1 function in the sencond. h file. How can I call the play1 function in the first. c file? Whether it is wrong or not. This involves another feature of the C language: Storage Class specifiers. The storage class specifiers of the C language include the following:

Description UseMethod
Auto Only allowed in Block Variable Declaration,Indicates that the variable has a local lifetime..
Extern Appears in the top layer or block external variable functions and variable declarations, indicating that the declared object has a static lifetime,The Connection Program knows its name..
Static It can be placed in the function and variable declaration.,When defining a function,Only used to specify the function name,Instead of exporting functions to linked programs,In function declaration,It indicates that there will be declared functions later.,Storage TypeStatic.In data Declaration,It always indicates that the defined declaration is not exported to the Connection Program.
Undoubtedly, second in routine-5. H and first. in H, we need to use the extern identifier to modify the declaration of the play1 function. In this way, the play1 () function can be exported to the Connection Program, that is, whether in first. the C file is still called in second. c file calls, the Connection Program will be very smart according to our will, connect him to first. the play1 function in the C file does not have to be defined in second. the C file also needs to write the same play1 function. however, there is a small problem. In routine-5, we didn't use the extern flag to modify play1. Another problem is involved here. The C language has the default Storage Class Identifier. c99 specifies that all top-level default Storage Class Identifiers are extern. so it turns out, haha. think back to the example 4, which is also a good risk. In the case of ignorance, we mistakenly hit it and used the extern modifier; otherwise, we would be in the first. if the play1 function declared in H is not exported by the connected program, we cannot find its actual location when calling play2. how can we differentiate Which header file is included in the corresponding . C File Definition , Which one does not? ?This may not be necessary, because no matter which file is defined, the smart Connection Program will help us find it and export it to The Connection Program, but I think it is really necessary. because we need to know what the specific content of this function is and what functions it has. I may want to modify it when new requirements exist. I need to find the definition of this function in a short time, let me introduce the individual rules in C language. : In . H Functions declared in the file , If . C File Definition , So when we declare this function , Not used Extern Modifier , If , It must be displayed Extern Modifier .In this way. in the H file, we will see two types of function declaration. the functions with extern are simple and clear. One is to reference external functions and the other is to define their own life. the final result is as follows: sencond. the H file extern play1 (); so many of the above are for functions, but in fact. H files are not used by functions. open one of our projects. in the H file, we found that apart from functions, there are other things, that is, global variables. in large projects, the use of global variables is inevitable, for example, in the first. c needs to use a global variable g_test. in H, define tpye g_test. similar to the use of functions, in second. in C, our developers found that they also need to use this global variable, and they need. in C, what should I do? Yes, we can follow the processing method in the function, in second. in H, the tpye g_test is declared again. According to the use of extern and the default storage type in C Language, The tpye g_test declared in the two header files is actually extern, that is to say, we don't have to worry about it. The Connection Program will help us deal with everything. but how can we distinguish between global variables, which is definition Declaration and which is reference declaration? This is more complex than functions. Generally, there are several models in the C language: 1, Initialize statement ModelIn the top-level declaration, the initialization statement is yes, indicating that the Declaration is a definition Declaration, and other declarations are reference declarations. Only one definition Declaration can be found in all C language files. According to this model, we can define the following tpye g_test = 1 in first. h; then we are sure that the definition declaration is in first, and all other declarations are reference declarations. 2 , Omitted storage type description In this model, all reference declarations including storage classes to be displayed Extern The storage class specifiers are omitted in the unique definition declaration of each external variable.This is similar to our method for processing functions. There is also a need to note that it is not very relevant to this article, but a friend in the previous paragraph encountered this problem. I believe many people will encounter this problem, that is, the global variable of the array. The problem he encountered is as follows: when declaring the definition, the definition array is defined as follows: int g_glob [100]; When referencing the Declaration in another file, the Declaration is as follows: int * g_glob; in VC, it can be compiled. In this case, we are all vague and note that arrays are similar to pointers, but they do not mean that the variables declared for arrays are pointers. The above mentioned program found a problem during runtime. in the file that references the Declaration, when using this pointer, it always prompts a memory access error, in the past, our connection program did not equate pointers with arrays. During the connection, we did not regard them as the same definition. Instead, we thought they were irrelevant two definitions, and of course there would be errors. The correct method of use is to declare the following in the reference Declaration: int g_glob [100]; and it is better to add an extern to make it clearer. Extern int g_glob [100]; in addition, it should be noted that the reference declaration can be simplified as follows because the memory allocation is not required, so that when the length of the global variable needs to be modified, you do not need to modify all the reference declarations. Extern int g_glob ,. net and other languages and tools have a certain impact on C, but we can see that other languages cannot be replaced in the most important part of the computer, this field is exactly what we yearn for programmers who are obsessed with computers. Well, after reading the article, I should have a better understanding of the role of C header files. If you already know this, it's just a review. If you didn't know it, congratulations! Now I have learned some skills and knowledge.

For the definition and declaration of global variables, there is actually another solution. You may have guessed it as early as possible: Yes, it is implemented using the macro definition technique. for example,. H files include:
# Ifdef aaa
Int I = 0;
# Else
Int I;
# Endif
In the. c file, there are the following statements:
......
# Define aaa
# Include "A. H"
......
For any other header file or. C source file containing a. h file, you only need to directly include a. h.
......
# Include "A. H"
......
In this way, the variable can be defined once in the. c file, and the variable can be declared in other files.
Of course, you can decide which file contains a. h according to your own needs, but what I want to say is
In different files of the same project that need to contain a. h, you can only define AAA once. Otherwise, when you connect to these target files
Repeated definition errors, even if your individual target file compilation has no problems.

Of course, this is only about the declaration of global variables. We strongly recommend that you use macro definitions in the header file to prevent repeated inclusion of the entire header file. Of course, most C-language programmers understand this technique.
# Ifndef xxx
# Define xxx

# Endif
This will make your program more stable and greatly reduce unnecessary troubles...

Finally, we will give you a little attention to the use of global variables. This is just a suggestion, or a programming habit.
1) all global variables start with G _ and are declared as static type as much as possible.
2) try to prevent cross-file access to global variables. If you do need to access the same variable in multiple files, the get/put function should be provided in the file where the variable is defined.
3) The global variable must have an initial value. The global variable should be initialized in a special function as much as possible.
4) if less than three functions are called, consider changing them to local variables.

If there is anything wrong with the text, please correct and learn from each other :)

For your security, please only open the URL with reliable source

Cancel website opening

From: http://hi.baidu.com/pepsi360/blog/item/07c92ba8764088baca130c37.html

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.