Here is an example:
my_main.cpp:
Code:
#include<iostream>
#include "Functions.h"
using namespace std;
int main()
{
int a = 10;
display(a);
return 0;
}
Functions.h:
Code:
//Functions.h
void display(int a);
Functions.cpp:
Code:
#include<iostream>
using namespace std;
void display(int a)
{
cout<<a<<endl;
}
When you #include a header file(i.e. a .h file) in your program, the include statement is replaced with the contents of the header file. The function header that is included above alerts the compiler something to the effect of: "hey, this function is defined in another file---go look for a .cpp file with the function definition in it."
To show that an #include statement just inserts the code in the .h file, change my_main.cpp to this:
Code:
#include<iostream>
void display(int a);
using namespace std;
int main()
{
int a = 10;
display(a);
return 0;
}
...and you should see that the program still works.
You can also just do this:
Functions.h:
Code:
#include <iostream>
using namespace std;
void display(int a)
{
cout<<a<<endl;
}
my_main.cpp:
Code:
#include<iostream>
#include "Functions.h"
using namespace std;
int main()
{
int a = 10;
display(a);
return 0;
}
which includes the whole function in my_main.cpp. However, the norm is to have .h files with just function headers or class declarations and separate .cpp files for function defintions.
As a matter of course, header files have what are called 'preprocessor directives' surrounding the code, which prevents a header file from being included more than once, which at the very least would cause code duplication, and at worst can cause errrors when there are definitions in the included file. In C++, you can't define something twice, e.g.
int a = 10;
int a = 10;
will cause a redefinition error--the same thing happens with functions. Here is an example of preprocessor directives that prevent including a file more than once:
Functions.h:
Code:
//Functions.h
#ifndef FUNCTIONS_H //can be any unique identifier
#define FUNCTIONS_H
void display(int a);
#endif
With those preprocessor directives, you can have this in my_main.cpp:
#include "Functions.h"
#include "Functions.h"
and Functions.h will only be included once. You may think that is a stupid example because you would never do that, but when you have a large number of files it can be almost impossible to tell when you may be including the same header file more than once.