Possible Duplicate:
In C++ why have header files and cpp files?
I was reading some KDE tutorials for creating basic plasma widgets and other QT stuff. One thing that I noticed is almost all the programs has a .h and .cpp with header file included in the cpp file.
The basic thing that I get is to minimize the clutter in the file and make the code more readable.
My question is what things should I put in a .h file and .cpp file writing a program and how it is going to benefit me in improving my code.
For example – I’ve created 3 files , add.h, add.cpp and pass.cpp – Now add.h has the function while other 2 have definition.
Add.h
#include <iostream>
using namespace std;
int add (int x,int y);
Add.cpp
#include "add.h"
int main() {
add (int x, int y) {
int z = x+y;
cout<<"Add is "<<"\t"<<z;
}
return 0;
}
Pass.cpp
#include "add.h"
add (3,4);
However this doesn’t work , judging from the answer here Why have header files and .cpp files in C++?
contents of add.h are automatically copied yet I get several errors.
Write all the functions completely in your
".cpp"file and write it first of all in your program.In your
".h"file, write just the proptype, that is the declarations of your functions. Make this".h"file at the end of your program. And don’t forget to write a semi-colon(;) at the end of each function prototype.This is a good programming practice and it gives you the benefit of writing the code once in these separate files and using their code across your entire project or any other number of files.
Suppose you have a file
"myProgram.cpp"andmyProgram.h, you can just include this one line at the beginning of any program to use its code.#include "myProgram.cpp".It works well when you have a number of functions and declarations in your file. If you have a small piece of code, there is no need of creating these separate files.