In C (or a language based on C), one can happily use this statement:
#i开发者_StackOverflow社区nclude "hello.h";
And voila, every function and variable in hello.h
is automagically usable.
But what does it actually do? I looked through compiler docs and tutorials and spent some time searching online, but the only impression I could form about the magical #include
command is that it "copy pastes" the contents of hello.h
instead of that line. There's gotta be more than that.
Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the ;
, though.
Your specific example is covered by the spec, section 6.10.2 Source file inclusion, paragraph 3:
A preprocessing directive of the form
# include
"
q-char-sequence"
new-linecauses the replacement of that directive by the entire contents of the source file identified by the specified sequence between the
"
delimiters.
That (copy/paste) is exactly what #include "header.h"
does.
Note that it will be different for #include <header.h>
or when the compiler can't find the file "header.h"
and it tries to #include <header.h>
instead.
Not really, no. The compiler saves the original file descriptor on a stack and opens the #include
d file; when it reaches the end of that file, it closes it and pops back to the original file descriptor. That way, it can nest #include
d files almost arbitrarily.
The # include
statement "grabs the attention" of the pre-processor (the process that occurs before your program is actually compiled) and "tells" the pre-processor to include whatever follows the # include
statement.
While the pre-processor can be told to do quite a bit, in this instance it's being asked to recognize a header file (which is denoted with a .h
following the name of that header, indicating that it's a header).
Now, a header is a file containing C declarations and definitions of functions not explicitly defined in your code. What does this mean? Well, if you want to use a function or define a special type of variable, and you know that these functions/definition are defined elsewhere (say, the standard library), you can just include (# include
) the header that you know contains what you need. Otherwise, every time you wanted to use a print function (like in your case), you'd have to recreate the print function.
If its not explicitly defined in your code and you don't #include
the header file with the function you're using, your compiler will complain saying something like: "Hey! I don't see where this function is defined, so I don't know what to with this undefined function in your code!".
It's part of the preprocessor. Have a look at http://en.wikipedia.org/wiki/C_preprocessor#Including_files. And yes, it's just copy and paste.
This is a nice link to answer this question.
http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Usually #include and #include "path-name" just differs in the order of the search of the pre processor
精彩评论