why and when we use #include?


#include is used to add code into your file during compiling.

So, for example, in order to use a function you muse first declare it (tell the compiler that it exists and what arguments it takes). There are a ton of libraries out there with pre-compiled code. In order to use any of them, you need to '#include' a header file with those function declarations in them.

So, if you have a set of functions/classes that you have written that you think may be nice to have as a library, you can move all the function/class declareations into a header file or files and then you can include them in other code.

the #include directive lets you include code into your code when you compile. So long as the contents of the file fit syntactically with the program you can use it to include any file.

For example often it is nice to have someone with a better grasp of the language to do your text for you. So you can have them put all of their text into a text file (with quotes at the beginning and end of each line). like so:
1"\tThis is some text that is maintained by "
2"some artsy type english majors who do "
3"not know how to code at all, but who "
4"can spell and know grammar. \n"
sometext.txt

then you can include this into your code like so:
01#include <iostream>
02 
03char text[] =
04#include "sometext.txt"
05;
06 
07int main(void) {
08    std::cout << text << std::endl;
09    return 0;
10}


Now I don't recommend doing things this way. I mean that author could insert code into your program (insert all kinds of things -- most of them probably bugs). My point was that so long as the contents of the file fit the syntax of the program you can include anything you would like.

Generally, this is used to include logical units such as library function declarations and classes. Sometimes it is used to include code snippets. Sometimes it is used to include data.