What does #include actually do?

后端 未结 6 1496
广开言路
广开言路 2020-12-15 04:25

In C (or a language based on C), one can happily use this statement:

#include \"hello.h\";

And voila, every function and variable in

相关标签:
6条回答
  • 2020-12-15 04:28

    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

    0 讨论(0)
  • 2020-12-15 04:36

    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-line

    causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters.

    0 讨论(0)
  • 2020-12-15 04:39

    Not really, no. The compiler saves the original file descriptor on a stack and opens the #included 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 #included files almost arbitrarily.

    0 讨论(0)
  • 2020-12-15 04:42

    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.

    0 讨论(0)
  • 2020-12-15 04:47

    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.

    0 讨论(0)
  • 2020-12-15 04:51

    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!".

    0 讨论(0)
提交回复
热议问题