Differences between the. C and. h files (the relationship of the header file to the implementation file ~)

Source: Internet
Author: User

  differences between. C and. h Files

A simple question: the difference between. C and. h files
After learning the C language for a few months, I felt more and more confused. The same subroutine, can be defined in the. c file, can also be defined in the. h file, then what is the difference between the two files in usage?

2 Floor:
The subroutine is not defined in. h.
The function definition is to be placed in. c, and. h is declared only. Otherwise, multiple references can occur, and a duplicate function definition error occurs.

3 Floor:
. h only declares that no code is generated after compilation

4 Floor:
This is done to achieve the modularity of the software
Make the software structure clear, but also easy for others to use the program you write

Purely in the C language syntax, you can of course put anything in. h, because #include is exactly equivalent to putting. h files ctrl-c ctrl-v into. C

. h should be some macro definitions and variables, function declarations, tell others what your program "can do, how to use"
. c is the definition of all variables and functions, telling the computer how your program "should be implemented"

5 Floor:
Of course, if an. h is included in multiple. C
And there is a definition of an object (variable or function) in the. h, a duplicate definition error occurs.
Declarations can be infinitely many times, defined only once
6 Floor:
In general, a C file should be a module
If your program has only one module (just a C file), you can not create an H file.

Otherwise your module must not be independent, and the implementation of your module will be called by another module. At this time, you'd better generate a header file (h file), in the header file you can declare that your functions are public. When other modules contain your header files, you can use your public statements.
7 Floor:
A c corresponds to an H, which makes it easy to manage.
For example, if you have 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, writing functions in H files doesn't matter, it just doesn't fit the habit. As long as the above format to write, an H file to add how many times it doesn't matter, hehe

8 Floor:
It's just a convention.
In the compiler,. C and. h are no different,. C and. h are completely dependent on the programmer, but for your program to be able to understand later and others can understand, please abide by the general agreement, these Conventions in front of the prawns have spoken a lot.
This is like a car on the road to the right to exercise, is a man-made agreement, the car (compiler) itself does not know whether they are on the left or the right to exercise.
If you like, you can also use any suffix to name source files and header files, but doing so may lead to integrated compilation and debugging environment strikes, you have to write your own makefile files.
9 Floor:
Thank you very much, hero, but I'm getting confused now.
1, when a function to be used frequently (for example, more than 10 C files to use it), I usually put in the H file, and in front of the __inline. For __inline functions, many C files can include this H file, but it seems to be only an H file include, If there are two H files that include it, a compilation error occurs.
2, some array variables, the size may be up to more than 10 k, and to assign the initial value, which is not placed in the C file, or people are blindfolded.
3,
#ifndef _feed_dog_h
#define _feed_dog_h

extern void Feed_dog (void);

#endif
Mohanwei brother, is this the case, this feed_dog.h can be many times to be include?
11 Floor:
#ifndef _feed_dog_h//If the macro "_feed_dog_h" has not been defined so far
#define _FEED_DOG_H//defines the macro "_feed_dog_h"

extern void Feed_dog (void); Declaring 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.


See an article on the Internet. H and. c articles, feel good, and share with you.


To put it simply
In fact, to understand the C file and header file is different, first need to understand the compiler's work process, in general, the compiler will do the following several procedures:
1. Preprocessing phase
2. Lexical and grammatical analysis phase
3. Compile phase, first compiled into pure assembly statements, and then compiled into a CPU-related binary code, the generation of various target files
4. Connection phase, the individual target files in each section of the code for absolute address positioning, to generate a specific platform-related executables, of course, the final can also be used to generate pure binary objcopy
The file format information is removed.

The compiler is compiled at compile time in the C file, that is, if your project does not have a C file, then your project will not compile, the connector is in the target file unit
, it will be one or more target files for function and variable relocation, generate the final executable file, the development of the program on the PC, generally have a main function, which is the individual compiler
The Convention, of course, if you write your own connector script, you can not use the main function as a program entrance!!!!

With these basics in order to generate a final executable file, you need some target files, that is, c files, and these C files need a main
function as the entrance to the executable program, then we start with a C file, assuming that the C file reads as follows:
#include <stdio.h>
#include "Mytest.h"

int main (int argc,char **argv)
{
Test = 25;
printf ("test.................%d\n", test);
}

The contents of the header file are as follows:
int test;

Now let's take this example to explain the compiler's work:
1. Preprocessing phase: The compiler takes the C file as a unit, first reads the C file, finds that the first sentence and the second sentence contain a header file, and will look for the two in all search paths
File, when found, will be the corresponding header file to process macros, variables, function declarations, nested header file inclusion, detection dependencies, macro substitution, see if there is a duplicate definition
With the declaration of the situation, and finally all of those files in all the things scanned into the current C file, the formation of an intermediate "C file"

2. During the compilation phase, the test variable in the header file is scanned into an intermediate C file in the previous step, then it becomes a global variable in this file.
All the variables of this intermediate C file are allocated space, the functions are compiled into binary codes, the target files are generated according to the specific target file format, the target text in this format
Each global variable, the symbolic description of the function, the binary code is organized into a target file according to a certain standard

3. Connection stage, the previous step genetic the various target files, according to some parameters, the connection to generate the final executable file, the main task is to relocate the various target file functions, variables
And so on, equivalent to the binary code in a target file in a certain specification to a file


Go back to the topic of what the C file and the header file are written on:
In theory, the C file and the contents of the header file, as long as the C language supports, no matter what can be written, such as you write in the header file function body, as long as in any one C file contains this
The header file can compile this function as part of the target file (the compilation is in C file, and if it is not included in any C file, this code will be a dummy
, you can do function declaration, variable declaration, struct declaration in C file, this is not a problem!!! Then why do you have to split the header file with the C file? And why are they usually in the first piece?
In the function, variable declaration, macro declaration, struct declaration? And in the C file to do variable definition, function implementation?? The reasons are as follows:

1. If you implement a function body in a header file, if you reference it in multiple C files and compile multiple C files at the same time, connect the resulting target file to an executable file
, in each C file referencing this header file generated by the target file, there is a copy of this function code, if the function is not defined as a local function, then when connected, will be sent
If you have more than one function, you will get an error.

2. If a global variable is defined in the header file and the global variable is assigned an initial value, then there is also a copy of the same variable name in the C file that references the header file, and the key is that this variable is
Given the initial value, so the compiler will put this variable into the data segment, and eventually in the connection phase, there will be more than one variable in the data segment, it can not unify these variables into a variable, that is, to allocate only one space for this variable, rather than multiple space, assuming that the variable in the header file does not have an initial value, The compiler will put it into the BSS segment, and the connector will have multiple
A variable with the same name allocates only one storage space

3. If you declare a macro, struct, function, etc. in the C file, then I want to reference the corresponding macro in another C file, the struct, you must do another repetition of the work, if I change a C
A statement in the file, then forgot to change the other C files in the declaration, this is not a big problem, the logic of the program becomes you can not imagine, if you put these public things
In a header file, want to use its C file just need to reference one on OK!!! This is not convenient, to change a statement, only need to move the first file on the line

4. Declare the structure, function, etc. in the header file, when you need to encapsulate your code into a library, let others use your code, you do not want to publish the source, then how others use your library
It? How do you use each function in your library? One way is to publish the source code, other people want to use how to use, the other is to provide a header file, someone else from the file to see your
function prototype, so that people know how to call the function you write, just as you call the printf function, what are the parameters inside? How do you know that? It's not a family.
The relevant statement in the header file!!! Of course, these things have become the C standard, even if you do not look at someone's head file, you can know how to use


What is the difference between the ". h" File and the ". C" file in the program source code??
In a program source code, saw the Udp.h file and saw the Udp.c file, do not know what is the relationship between the two? What difference does it have? which expert came to help, thank you.

The first-level best answer. C is the source file for the C language series, which exists as text, while the. h series is the header file, which is the file that stores functions and global variables in the C-series, because the functions in C are encapsulated and cannot see their code.

The relationship between the header file and its implementation file
I read an explanation on the internet today. H and. C (. cpp) articles, I feel that after reading some of the place is inappropriate, hereby according to my understanding, give beginners some guidance ~
Do you understand the simple meaning?
About the relationship between the two before, from N years ago to say a long long ago,once aupon a time ....
It was a forgotten age, in which the compiler knew only. C (. cpp)) files without knowing. h is the age of what.
At that time, people wrote a lot of. C (. cpp) files, and gradually, people found that the declarations in many. C (. cpp) files are the same, but they have to put them into each. C (. cpp) file in a single word and repeatedly. But even more frightening is that when one of the declarations changes, you need to check all the. C (. cpp) files and modify the declarations, ah ~ It's the end of the world!
Finally, someone (perhaps someone) 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 (. 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 (. cpp) file, it is named "header file" and the extension is. h.
From then on, the compiler (in fact, the preprocessor) knows that the world has a. C (. cpp) file, plus a. h file, and a command called # include.

Although a lot of changes have occurred later, but this usage has continued to this day, only a long time, people will forget the reason for that year.

Mention the head file, say it's function ~
Think of a brief description of the role of Lin Rui Gg in the high-quality C + + programming overhead file:
(1) The library function is called through the header file. In many cases, the source code is inconvenient (or not) to the user, as long as the user is provided with a header file and a binary library. The user only needs to invoke the library function according to the interface declaration in the header file, without having to worry about how the interface is implemented. The compiler extracts the appropriate code from the library.
(2) header file can enhance type safety check. If an interface is implemented or used in a way that is inconsistent with the declaration in the header file, the compiler will point out the error, a simple rule that can greatly reduce the burden of debugging and error-changing by the programmer.


Preprocessing is the predecessor of the compiler, and the function is to set the program modules stored in different files into a complete source program.
#include本身只是一个简单的文件包含预处理命令, that is, to put the following file of the include in this command here, in addition, there is no other use (at least I would like to think).


I have a smile on the universe of the views of the brother, very agree, the basis of the east must be clear.
I'm following the case of a smile Brother's example, complete his some confusing time ~

Example:
A.h
void Foo ();


A.c
#include "a.h"//My question came out: this sentence is to, 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:
A.C in the #include "a.h" This sentence is not redundant?
1. Why do you often see the xx.c include the corresponding xx.h?
2. If the A.C is not written, then does the compiler automatically bind the contents of the. h file with the. c file of the same name?
3. The third question I changed to him: if the A.C does not write Include<>, then the compiler will not automatically put in the. h file with the name of the. c File binding together?

Here is the exact words of a smile:

From the C compiler's point of view,. h and. C are clouds, that is, the renamed. txt,. doc is not a big difference. In other words, the. h and. C Have nothing to do with it. The declarations of variables, arrays, and functions defined in the. c file with the same name are generally placed in H. Declarations that need to be used externally by. C. What's the use of this statement? Just make it easy to quote where these statements are needed. Because #include "xx.h" this macro its actual meaning is to delete the current line, the contents of the xx.h is inserted in the current line position intact. Because there are so many places to write these function declarations (every call to a function in XX.C is declared all at once), a macro that uses #include "xx.h" simplifies many lines of code--and lets the preprocessor replace itself. In other words, xx.h actually just makes the call where the function declaration in the XX.C needs to be written (fewer lines can be written), as for the include. h file who, is it. h or. c, or the. h with the same name. C, there is no inevitable relationship.
So you might say, "Ah?" I usually just want to call a function in xx.c, but include the Xx.h file, is not a macro replacement after a lot of useless declarations? Yes, it does introduce a lot of rubbish, but it saves you a lot of ink, and the whole layout looks more refreshing. It is this truth that the fish and bear cake cannot be combined. Anyway, more statements (. h is generally only used to put the declaration, but not defined, see my book fixing "cross the road, look Around") also harmless, do not affect the compilation, why not?
Turn back and look at the top 3 questions, very good answer it?

Its solution is as follows:
Answer: 1. Not necessarily. This example is obviously superfluous. But if the functions in. c also need to call the same. C, then this. C will often include. h with the same name, so that there is no need to worry about the order of declarations and calls (the C language requires that it must be declared before it is used, and include has the same name.) h is usually placed at the beginning of. C. There are many projects that even use this notation as code specifications to standardize clear code.
2. Answer: 1 has already answered.
3. Answer: No. The person who asks this question is definitely unclear, or wants to mix water to touch fish. Very annoying is a lot of Chinese test out of this bad problem, for fear that others have a clear concept, absolutely to the examinee dizzy.

over!

To be clear here, the compiler compiles according to the compilation unit, the so-called compilation unit, refers to a. c file and all the. h files it contains. The most intuitive understanding is that a file, a project can contain many files, which have a program entry point, That is what we usually call the main () function (of course, you can not have this function, the program can still start, see my blog in detail). In the absence of this program entry point, the compilation unit only generates the object file (. o file, under Windows called. obj).

This example contains a total of two compilation units, A.C,MAIN.C, which, as I said, only generate their own. o files at compile time. This phase does not have any relationship with other files.
The Include preprocessing directive occurs during the preprocessing phase (the previous compilation phase, just a precursor handler for the compiler).


. H. C is not necessarily a cloud, out of the compiler to talk about these have no meaning, put aside the deeper of these, for example, the OS how to start this file, PE structure (under Linux for Elf) and so on
The compiler must first identify the file before it is possible to compile it, which is the premise. If you change its extension then your compiler can still know it? ~ rise to a higher level to look at this problem, xx brother Said is also good ~ I think xx brother said the meaning of the two can not because of the same name to think what the relationship between the two, The name can be casual ~
The connection between the two, I said earlier, is due to historical reasons, coupled with the habits of people, I think no one would like to remember so many filenames it. (Take me for an example, a number
According to the table if more than 30 fields, I think the head is big, now make the table has as many as hundreds of fields, I really hope that high man research what good way to ~, also let our world better some ~)

The third problem of a smile is very representative, many times on the internet to see, now the compiler is absolutely not so smart, and there is no need to do so. Let's talk about the compiler's process. (I think beginners have a problem with this, that is, for the compilation process. H. C (. cpp) changes are not well understood,)

Here's a simple example to talk about.
Examples are as follows:
A.h
Class A
{
Pubic
int f (int t);
};

A.cpp
#include "A.h"
int a::f (int t)
{
return t;
}

//main.cpp
#include    "A.H"
void   Main ()
{
      a    A;
      A.F (3);
}
During the preprocessing phase, the preprocessor sees the # include "filename" to read this file in, such as it compiles main.cpp, see #include   "A.h", It reads the contents of the A.H, and it knows that there is a class A that contains a member function F, which takes an int parameter and returns the value of an int type. It is easy to compile the a   a line to understand, it knows is to take a this class on the stack to generate an object. Further down, it knows the following to call A's member function f, the parameter is 3, because it knows that the function to a number of parameters, this 3 exactly match, it is just put it on the stack, generate a call f (int) function of the instruction (generally may be a word called), as for this f (int) The function is exactly where, it does not know, it is left empty, the link is resolved again. It also knows that the F (int) function is going to return an int, so maybe it's also ready for that (in the example, we don't use this return value, and maybe it doesn't handle it). Then down to the end of the file main.cpp compiled, generated main.obj. There is no need to know the content of A.cpp throughout the compilation process.
In the same vein, the compiler compiles a.cpp, compiles the F () function, compiles the a.cpp, and compiles the F () without any other control. Generated a a.obj.
The last step is the link stage, and the linker links all. obj generated by all. CPP in the project.
In this step, it clarifies the address where the F (int) function is implemented, and fills in the correct address for the address where the main.obj is empty. The executable file Main.exe is eventually generated.

Do you understand? I do not understand that more than a few words, we are learning to compile the principle of the time all know that the compiler is staged, each phase of the source program from one representation to another representation, in general, the following sequence: source program, lexical splitter---parser, Target program, code generator, code optimizer, middle code generator, Semantic Analyzer.
The two main activities involved in this intermediate 6 activities are: the symbol Manager and the error handler.
In the root cause, here is a symbol table in the east to let you possessed the same do not understand, in fact, the symbol table is a data structure. The basic function of the compiler is to record the identifiers used in the source program and collect various property information related to each identifier. The attribute information indicates where/type the identifier is stored/ Scope (valid at that stage) and so on, in layman's words, when the compiler sees a symbolic declaration, such as your function name, it will put it in the symbol table to register ~ ~ The symbol table contains the entry address of your function, the number of parameters, return information and so on a pile of things ~ In the connection phase, the symbolic table in the project is processed and the corresponding processing relation is called, which is what we usually call the solution reference.
Through the front, do not know it or not?

Finally quoted the end of the brother xxx three points:
It is easy to understand grammar and concept, and it is difficult to say difficult. The trick has three points:
1. Do not dizzy head work, take the time to think more, read more books;
2. Read books, ask people to ask the strongman. Bad books and rotten people will give you a wrong concept, misleading you;
3. Qinnengbuzhuo is a good training, a point of hard work only;

If you think that the. c and. h files are just names that are not the same, it is hard to understand the superficial point. With op history it seems that the development of language is trending with OOP. h file appears. A bit of a kind of nature in the inside. h file is well concealed. This is not difficult to find. As long as the big open C own. h file look, it is obvious. So, I agree with xxx brother think the universe smile superficial.

However, from another perspective.:

(As for the implementation of the compiler. I don't know yet, but. I believe. Elephant)
A.cpp
#include "A.h"
int a::f (int t)
{
return t;
}
Such a program does not appear .... So now people have to understand. h and. c are simplified. There is also a bit of history and the influence of the Times.


The younger brother is dull. I've seen it a few times.
Now summarize: (There is no wrong please PK)

1. The header file can pre-tell the compiler some necessary declarations, so that the compiler goes on smoothly, before the connection is implemented. The actual definition does not necessarily occur.
The meaning of the header file is
A. Make the procedure concise and clear.
B. Avoid repeatedly writing the same declaration code.
2.**.C and **.h files are not necessarily linked.
This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/bm1408/archive/2006/02/22/606382.aspx

Differences between the. C and. h files (the relationship of the header file to the implementation file ~)

Related Article

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.