I understand that I have to put a function prototype somewhere, but where? |
The compiler must know about the function before it has to call it. To do this you either declare it before it is used, or you define it before it is used.
Because you are using a library, the definition is in that library, so you must declare it before it is used. Anywhere you like. This, for example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<iostream>
using std::cout;
int main()
{
int a,b;
a = 3;
b = 4;
int Add(int i1, int i2);
cout<<Add(a,b);
return 0;
}
|
However, ramming them in the middle gets untidy, so how about at the top?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include<iostream>
int Add(int i1, int i2);
using std::cout;
int main()
{
int a,b;
a = 3;
b = 4;
cout<<Add(a,b);
return 0;
}
|
In fact, let's declare all of them:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include<iostream>
int Add(int i1, int i2);
int Substract(int a, int b);
int check_function(int a);
using std::cout;
int main()
{
int a,b;
a = 3;
b = 4;
cout<<Add(a,b);
return 0;
}
|
You know, even that seems a big messy, and it requires the person using the library to manually type in the declarations of functions. What if they get it wrong? Or forget one? Let's make a new header file:
functions.h
1 2 3
|
int Add(int i1, int i2);
int Substract(int a, int b);
int check_function(int a);
|
and then we can just #include that header file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<iostream>
#include "functions.h"
using std::cout;
int main()
{
int a,b;
a = 3;
b = 4;
cout<<Add(a,b);
return 0;
}
|
Hey, just like all the other headers! It declares all the functions and we don't have to worry about it. Now, if you ever distribute the library, you can distribute the compiled library, and the header file, and everyone will easily be able to use the library.
This is why we have header files, and it's why libraries come with header files to #include.