Generally, as you said, there are two types of file used in C++ programming. Files with the extension .h are 'header' files, and the extension .cpp denotes a main C++ file.
Now, header files are mostly used for empty declarations of functions and global variables, before they're used. This is so that when a .cpp file uses the #include directive with the name of that header, it can use the functions (etc.) declared in that header without having the code that the function contains.
For example:
1 2 3 4 5 6 7 8 9 10
|
// functions.h
// Declarations of functions for other parts of the program to use.
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int aFunction(int a, int b);
int anotherFunction(int a, char* b);
#endif
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
// functions.cpp
// Actual code for the functions.
#include <stdio.h>
int aFunction(int a, int b)
{
return a+b;
}
int anotherFunction(int a, char* b)
{
sprintf(b, "%d", a);
return 1;
}
|
The header functions.h can now be included in a .cpp file:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
// main.cpp
#include "functions.h"
#include <stdio.h>
int main(int argc, char** argv)
{
printf("%d + %d = %d", 3, 4, aFunction(3, 4));
char str[10];
anotherFunction(4, str);
printf("\n%s", str);
return 0;
}
|
This method of putting declarations into .h files is useful, because it means you can compile different sections of your code separately, without having large segments of code depending on each other.
functions.cpp can be compiled and maintained separately from main.cpp, so long as functions.h contains the correct declarations.
Also, in functions.h, "#ifndef FUNCTIONS_H", "#define FUNCTIONS_H" and "#endif" is used in case the header is included more than once. If the header's already been included, then the code between these preprocessor statements will be ignored. This prevents multiple declarations.
Hope this helped a bit.