A function may only be defined once, that is, you can only give the function a body a single time:
Code:
// mystuff.cpp
int doThis ( int x )
{
// This is the body
}
void doThat ( int x )
{
// Brackets mean a function definition
}
Now, in your main source you want to use these functions, but how do you know their names? How do you know their parameters and return values? Or more specifically, how does the compiler know that you're doing something legal? A function definition, or prototype.
Code:
// main.cpp
#include <iostream>
int doThis ( int x ); // I'm a function declaration
void doThat ( int x ); // Also called a prototype
int main()
{
std::cout<< doThis ( 1 ) <<'\n';
doThat ( 0 );
}
Now when you link main.cpp and mystuff.cpp together, the linker more or less tosses all of the separate files into a single file:
Code:
int doThis ( int x ); // I'm a function declaration
void doThat ( int x ); // Also called a prototype
int main()
{
std::cout<< doThis ( 1 ) <<'\n';
doThat ( 0 );
}
int doThis ( int x )
{
// This is the body
}
void doThat ( int x )
{
// Brackets mean a function definition
}
But before that happens, main.cpp doesn't know that doThis and doThat exist (they're in another file, so how can it?), so you need to declare them or main.cpp won't compile. You'll get an error about an undefined name.
Now let's say you want to call these functions in multiple files. You can declare them in all of the files because that's perfectly legal, but it's easier to just put the declarations in a header file and include it wherever you need it:
Code:
// mystuff.h
int doThis ( int x ); // I'm a function declaration
void doThat ( int x ); // Also called a prototype
Code:
// mystuff.cpp
int doThis ( int x )
{
// This is the body
}
void doThat ( int x )
{
// Brackets mean a function definition
}
Code:
// main.cpp
#include <iostream>
#include "mystuff.h"
int main()
{
std::cout<< doThis ( 1 ) <<'\n';
doThat ( 0 );
}
It breaks down like this: main.cpp gets declarations by including mystuff.h and gets definitions by linking with mystuff.cpp.