Jos Timanta Tarigan wrote:
> Im a little bit confused the difference between .h and .cpp. What is actually 
> a .h file? What is the difference between .h and .cpp?

You received two good answers that I know of so far, but here's my 
perspective on the question.

A .cpp file defines a "compilation unit," which is what the compiler 
compiles into object code and subsequently into an executable of some 
sort. Header files are not compiled directly, rather through inclusion 
into .cpp files.

Typically you put declarations in headers, and definitions in .cpp 
files. You would put the interface to your class in the header: the 
data, the methods (with no bodies), etc. then in a .cpp file you would 
define the methods: this is where your "real" code goes. You would 
prototype standalone methods in headers, and define them in .cpp files.

Tyler explained include guards, which help prevent declaring the same 
thing multiple times. For example, suppose you have a class that uses a 
std::vector. It also uses another class, and the other class also uses 
std::vector. You cannot define the vector twice, this is an error. 
Include guards make sure that it is only included once. His response 
goes into more detail, make sure you read it: this is an important 
fundamental to projects that span more than one source file.

This is a good question. I have read many books and tutorials on C++, 
both when I was learning and to see what people new to the language here 
in 2008 are using to learn. The compilation and execution environments 
are two things I rarely see explained well. Usually authors focus on the 
code itself, and skimp over any meaningful details on how to organize a 
project.

-- 
John Gaughan

Reply via email to