A simple question: The difference between .c and .h file
I have learned a few months of C language, but I feel more and more unknown. It is also a subroutine, which can be defined in the .c file, or it can be defined in .h file, what is the difference between these two files?
2nd floor: Subprogram should not be defined in .h. The function definition is to be placed in .C, and .h only makes a statement. Otherwise, multiple references will have a function repeated definition.
3rd floor: .h only to make a statement, do not generate the code 4 floor after compiling: This is to achieve software modularization make the software structure clear, and it is easy to use the program you write.
In the perspective of C language syntax, you can of course place anything at .H, because #include is completely equivalent to the .h file Ctrl-ctrl-v to .C
. h should be some macro definitions and variables, function declarations, tell others how your program "can do, how to use". C is the definition of all variables and functions, tell your computer "how to implement"
5th floor: Of course, if one. H is included. C contains and. There is an object (variable or function) definition, the duplicate definition is infinite, the definition can only be able to only 6th floor: 6th floor: In general, a C file should be a module if your program has only one module (only a C file), you can have an H file.
Otherwise your module is definitely not independent, and your module is implemented by other modules. At this time, you'd better generate a header file (H file), you can declare those functions in your header files. When other modules contain your header file, you can use your public claim. 7th floor: A c corresponds to a h, so that it is convenient for such a "feed_dog.c", then add a "feed_dog.h":
#ifndef _feed_dog_h # Define _feed_dog_h
EXTERN VOID feed_dog (void);
#ENDIF
In fact, the write function in the H file is not necessarily, but it is not a habit. Just follow the above formats, how many times there is no way, huh, huh
8th floor: It is only an agreement in the compiler, .c and .h are no difference, .c and .h how to use the programmer, but can understand after your program and others can also see I understand, please observe the universal agreement, these deprises have a lot of prawn. This is like the car to exercise on the road, it is human agreed, the car (compiler) itself does not know that he is Leaning on the left or by right. If you like, you can also name the source file and header file with any suffix, but you may cause the integrated compile compilation and debug environment strike, you have to write your Makefile file. 9 floor: Thank you very much Heroes, but I am getting more confused now. When a function is often used frequently (such as more than a dozen C files using it), I usually put it in the H file and add __inline. For front __inline function, many C files can include this H file, but it seems to be only one H file include, if there are two H file include it, there will be compilation errors. 2, some array variables, the size may reach more than a dozen K, and it is necessary to assign a first value, which is not placed in the C file, or not. 3, # ifndef _feed_dog_h # define _feed_dog_h
EXTERN VOID feed_dog (void);
#ndifmohanwei brother, is it fixed, this feed_dog.h can be ignited numerous times of INCLUDE? 11th floor: #ifndef _feed_dog_h// If there is no "_feed_dog_h" this macro #define _feed_dog_h //, defined "_feed_dog_h" this macro extern void feed_dog (void); // Declare an external function
#ENDIF / / "# ifndef" to this end
So, no matter how many times you define (even if you define multiple times in the same C file), there will be no conflict.
I saw an article about .h and .c, I feel good, post with everyone.
Simplely said that it is necessary to understand what the C file is different from the header file. First, we need to understand the work of the compiler. Phase 3. Compile stage, first compile into pure assembled statements, then compile into the CPU-related binary code, generate various target files 4. Connecting phase, the segment of each target file is definitely addressed, generated A specific platform-related executable, of course, in the end, it can also generate pure binary code with Objcopy, which is to remove file format information.
The compiler is based on C files, that is, if there is no C file in your project, then your project will not be able to compile, the connector is in units of target files, it will be one or more The target file is functioning with the relocation of the variable, generating the final executable, developed in the PC, generally has a main function, this is the convention of each compiler, of course, if you write the connector script You can use the main function as the program entry! ! ! !
With these basic knowledge, then return to Zheng, in order to generate a final executable, you need some target files, which is needed to be a C file, and a main function is needed as the entrance of the executable, then we will Starting from a C file, assuming this C file is as follows: #include
Int main (int Argc, char ** argv) {test = 25; Printf ("test .................% D \ n", TEST);}
The header file is as follows: int Test;
Now in this example, the compiler is explained: 1. Pretreatment phase: The compiler as a unit as a unit, first read this C file, find the first sentence and the second sentence to include a header file, will be all in all Looking for these two files in the search path. After finding, you will process macros, variables, function declarations, nested head files, and detect dependencies, macro replacement, and see if there are repetitive definitions. In the case of the statement, finally scan all the stuff in those files into this current C file, forming a middle "C file"
2. Compile stage, which is equivalent to scanning the Test variable in that header file into a middle C file, then the Test variable becomes a global variable in this file, and all this intermediate C is All variables of the file, the function allocation space, compile each function into binary code, generate the target file according to the specific target file format, in this formatted target file, the symbolic description of the function, the binary code is sure Standard organizations into a target file 3. Connection phase, the last stepped target file, according to some parameters, connection to generate the final executable file, the main job is to relocate the functions, variables, etc. of each target file, quite In combination of binary code in a target file, in one file
Go back to the topic of the C file and the header of the header: Theore in theory, the contents of the C file and the header file, as long as it is supported by the C language, whether you write anything, such as writing in the header file The function body, as long as any C file contains this header, you can compile this function into a part of the target file (compile is in units of C file, if this header is included in any C file, this code is Similar dummy), you can perform function declarations in the C file, variable declaration, structural statement, this is not a problem! ! ! Then why must you divide a header file and a C file? And why is usually functions in the header, variable declaration, macro statement, structural declaration? And in the C file, the variable definition is made, the function is implemented? ? The reason is as follows:
1. If a function body is implemented in the header file, if it is referenced in multiple C files, it is concluded that multiple C files are compiled, and the target files generated into an executable, in each reference In the target file generated by the C file of the header file, there is a code for this function. If this function is not defined as a partial function, then multiple identical functions will be found when connected, it will report an error.
2. If a global variable is defined in the header file, and the global variable is assigned, the same variable name is also present in multiple references this header file. The key is that this variable is assigned initial value. Therefore, the compiler will put this variable into the DATA segment, and finally in the connection phase, there will be multiple identical variables in the DATA segment. It cannot unifension these variables into a variable, which is only assigned a space for this variable. Instead of multiple spaces, assuming that this variable does not be assigned to the first value in the header file, the compiler will put it into the BSS segment, and the connector will only assign a storage space only for multiple parties variables in the BSS segment.
3. If you declare the macro, structure, function, etc. in the C file, then I want to reference the corresponding macro, structure in another C file, you must make a duplicate job, if I changed a C file A statement, then forgot to change the statement in other C files, this will not have a big problem, the logic of the program has become you unimaginable, if you put these public Dongdong in a header file In the middle, you want to use it with its C file just need to quote one is OK! ! ! This is inconvenient. When you change a statement, you only need to move your files. 4. Declare the structure, function, etc. in the header file. When you need to package your code into a library, let others use Your code, you don't want to announce the source code, how do people use your library? That is, how do you use your functions in your library? ? One way is to publish source, how to use it is how to use it, the other is to provide header files, others see your function prototype from the header file, so people know how to call your function, just like you call Printf functions Same, what is the parameters inside? ? How did you know? ? Not looking at the relevant statement in the header file of people! ! ! Of course, these stuffs become C standards, even if you don't look at people's head files, you can know how to use the program source code ".h" file and ".c" file ?? In a program source code, I saw UDP.H files and saw UDP.C files. I don't know what the two is related. What is the difference? Which master came to help, thank you Thank you.
The first-class best answer. C is the source file of the C language series, exists in text, and the series is the header file, that is, the function of the function and global variable in the C series, because the function in C is encapsulated. It is impossible to see its code.
The relationship between the header file and the implementation documents today see an explanation. H and .c (.cpp) article, I feel some places after reading, I will follow my understanding, give beginners some guidance ~ Do you understand the simple meaning? About the previous relationship, you have to say from N years ~ long long Ago, ONCE AUPON A TIME ....... That is a forgotten era, in the compiler Just know the .c (.cpp)) file instead of know what it is. At that time, people wrote a lot of .c (.cpp) files, gradually, people found that statements in a lot of .c (.cpp) files are the same, but they have to repeat one word Try these contents into each .c (.cpp) file. But more horrible is that when one of the statements have changed, you need to check all the .c (.cpp) files, and modify the declarations, ah ~ It is the end of the world! Finally, some people (maybe some people) I can't stand this torture, and he (we) extract the repeated part, put it in a new file, then knock in the statement of #include xxxx in the needed .c (.cpp) file. This way even if a statement has changed, no need to find and modify everywhere --- the world is still so beautiful! Because this new file, it is often placed in the head of the .c (.cpp) file, so give it a name "header file", the extension is. H. Since then, the compiler (in fact the pre-processor) will know In addition to .c (.cpp) file, there is a .h file, and a #include command.
Although there are many changes, this kind of usage has been continued, but it is just a long time, and people have forgotten the reason for the year.
When it comes to the header file, it is said that it is a short description of the high quality C / C programming of Lin Rui GG. (1) Call the library function through the header file. In many cases, the source code is inconvenient (or not allowed) to publish to the user, as long as the header file and the binary library are available to the user. Users only need to call the library function according to the interface declaration in the header file without having to care about how the interface is implemented. The compiler will extract the corresponding code from the library. (2) Header file enhances type safety inspection. If an interface is implemented or used, its way is inconsistent with the statement in the header file, the compiler will point out errors, this simple rule can greatly reduce programmers debugging, and the burden of changing the wrong. Prerequisites are the front drive of the compiler. The effect is to set the program module module stored in different files into a complete source program. # Include itself is just a simple file contains the pre-processing command, that is, put the incrude's back files to this The order is here, in addition to this, there is no other use (at least I think).
I agree with the view of the brothers of the Qiankun. The foundation of Dongdong must make it. I will tell the example of Qiankun smiled, and some of them are confused when I am confused.
Example: //a.hvoid foo ();
//a.c#include "a.h" // My problem came out: This sentence is, or not? Void foo () {return;}
//main.c#include "a.h" int main (int Argc, char * argv []) {foo (); return 0;}
For the above code, please answer three questions: Is there any excess this sentence in the #include "a.h" in A. 1. Why do I often see the xx.h corresponding to include INCLUDE? 2. If the A.C is not written, the compiler is not automatically binding what the .c file in the .c file in the same name? 3. I have changed him on the third question: If INCLUDE <> is not written in A.c, is the compiler that will automatically put things in the .h file with the same name. C?
Below is the original words of Qiankun:
From the perspective of the C compiler, .h and .c are floating clouds, which is called .txt, .doc has no big separate. In other words, it is .H and .C, no inevitable contact. It is generally in the same name. C file declaration as defined in the same name. C file, requiring the declaration of the .C external use. What is this statement? Just make it easy to use these statements. Because #include "xx.h" This macro does the actual meaning is to delete the current line, insert the content in XX.H, inserted into the current line. Since there are many places where they want to write these functions (every place in XX.C, you must declare a bit before use), so use #include "xx.h" this macro simplifies many line code - - Let preprocessors replace themselves. That is, XX.H is actually just let the function declaration in XX.C (can write a few lines), as for the incrude. H file is who is .H or .c, or this. H is the same .c, there is no necessary relationship. So you may say:? Then I usually just want to call a function in XX.c, but include xx.h file, isn't a lot of useless declarations after macro replacement? Yes, it really introduced a lot of garbage, but it saved you a lot of pens, and the entire layout also looks refreshing. Fish and bear's pauses are not available, that is, this truth. Anyway, some statements (.h is generally only used to put declaration, and do not define, see the "crossing the road, see") is also in harmless, and will not affect compilation, why not? Turning back and watch the three problems above, very good answer? Its answer is as follows: A: 1. Not necessarily. This example is obviously redundant. However, if the function in .c needs to call other functions in the same .c, then this .C tends to include the same name. H, which does not need to be worried about the declaration and call order (C language must be used before use Declaration, and include the same name. H is usually placed in .C's beginning). There are many projects even conforming this way to code specification to standardize clear code. 2. A: 1 has been answered. 3. A: No. People who ask this question are definitely unclear, or they want to mix fish. Very annoying is that many of China's exams are this kind of rotten question. I am afraid that others have a clear concept, and they must be dizzy.
OVER!
In this case, the compiler is compiled according to the compilation unit, the so-called compiler, refers to all .c files and all .h files it INCLUDE. The most intuitive understanding is a file, one project can Contains a lot of files, with a program's entry point, that is, the main () function we usually say (of course without this function, the program can be started, see my blog). Don't have this program entry point In the case, the compiler only generates the target file Object File (.o file, Windows is called .Obj).
In this example, there is a total of two compilation units, which are ac, main.c, and according to what I said, the compilation phase is only generated by respectively .o file. This phase does not have any relationship with other files. And Include This pretreatment command takes place in the pretreatment phase (the early compilation phase, just a front drive handler of the compiler).
.h .c is not necessarily a cloud, getting from the compiler, there is no meaning, throwing a deeper level, such as how OS starts this file, PE structure (linux is ELF), etc. Compiler first Identify this file to compile it, this is a premise. If you change its extension, then your compiler can also know it ~ Rising to a higher level to see this problem, XX brother is not bad ~ I think the XX brother is what the two cannot be said because the name is the same, the name is the connection between the two, I have said before, it is due to historical reasons. Adding people's habits, I don't want to remember so many file names. (Take me for an example, if more than 30 fields, I feel big, now Some up to hundreds of fields, I really hope that the high person has studied a good way ~, let our world better ~) The third question of Qiankun is very representative, many times When the current compiler is definitely not so smart, and there is no need to do it. Let's take the process of the compiler. (I think that beginners have questions, that is, for the compilation process .h .c Changes in (.cpp) are not very understandable,)
Below I said to give a simple example to talk ~ The example is as follows: //a.hclass a {pubic: int F (int T);};
//a.cpp#include "a.h" int A :: f (int T) {returnit t;}
//main.cpp#include "AH" void main () {a a; AF (3);} In the pre-processing phase, the preprocessor sees the #include "file name", read this file, such as it compile Main.cpp, see #include "ah", it reads the contents of AH, it knows, there is a class A, including a member function f, this function accepts an INT type parameter, returns an int type value . The next reciprocation is easy to read the A a this line, it knows that you have to generate an object on the stack. Next, it knows that the member function f of the following is to call A, the parameter is 3, because it knows this function to use parameters, this 3 is just match, then put it on the stack, generate one Call the F (int) function (generally a call), as for this F (int) function, where is it, it doesn't know, it is empty, then resolved when the link is linked. It also knows the F (int) function to return an int, so maybe it is ready for this (in the example, we don't use this return value, maybe it does not process). Then, the next to the file, main.cpp is compiled, generated main.obj. You don't need to know the content of A.CPP at all during the entire compilation process. Similarly, the compiler recompiles A.cpp, compiles the F () function, compiles A.CPP, it does not need to manage, compile F (). Generated a.obj. The last step is the stage of the link. The linker puts all the .obj links generated in the project. In this step, it clarifies the implementation of the F (int) function, putting main.obj. This address location fills in the correct address. Eventually the executable main.exe is generated.
Understood? Don't understand, then say a few words, we know when learning the principle of compilation, the compiler is dated in the stage, and each stage will convert the source program from one representation into another., General situation Under the order of the order: Source -> Less Law -> Syntax Analyzer -> Semantic Analyzer -> Intermediate Code Builder -> Code Optimizer -> Code Builder -> Target. One of these activities The two main activities involved are: Symbol Manager and Error Processor. For the reasons of root, there is a status of a symbolic table that makes you don't understand the same, in fact, the symbol table is a data structure. Compiler Basic features are to record the identifiers used in the source program and collect various attribute information related to each identifier. The attribute information indicates the storage location / type / scope of the identifier (which is valid at that stage) Information, popular saying, when the compiler sees a symbolic declaration, for example, your function name will put it in this symbol table to register ~ The entrance address of your function in the symbol table, Number of parameters, return information, etc. A stack of things ~ and in the coupling phase is mainly the symbolic table and call corresponding processing relationship in the project, that is, the decodes we usually say. After the previous, I don't know if it is understood? Three points of the end of the XXX brother: Make a clear grammar and concept, said that it is difficult to say. There are three points of tricks: 1. Don't worry about your head, you have to take a lot of thinking, read more books; 2. Read the book to be optimistic, ask people to ask a strong person. Rotten books and rotten people will give you a wrong concept, mislead you; 3. Diligence is a good training, a hard work is hard;
If it is considered .c and .h files are only the names are not the same. History. History of OP, the development of language is tend to appear with OOP..H file. Available in the nature of ..h.. The file has a hidden. This truth is not difficult to find. Just open C his own .H file, it is obvious. So, I agree that the XXX brother thinks that the skin smile.
However, from another aspect.:
(As for the implementation of the compiler. I haven't understood it yet. However. I believe.) //A.cpp #include "ah" int A :: f (int T) {Return T;} This program will not appear. .... Ha ha. So now people must understand. H and .C simplified. It is also a bit of a historical and era.
The younger brother is dull. After reading a few times, I finally understood. Now summary: (If you are right, please pk)
1. The header file can tell the compiler some necessary statements, so that the compiler will go smoothly, before the connection is achieved. The meaning of the actual definition is not necessarily, the meaning of the header file is in a. Bring the program, clear. B. Avoid repetition Write the same declaration code. 2. **. C and **. H files do not have an inevitable connection.