Q: Why do I have to use header files in C++?
A: Technically, you can put all your code into the .h file, but that is consider very bad coding. When C++ was created, computers didn't have the RAM or the processing power they have now, so the C++ compiler doesn't do as much "housekeeping" as more modern languages. The header files were created to help the compiler figure out how to put the various CPP files together without shooting itself in the foot.
Q: I get an error saying that there are multiple definitions of my class (or variable or function). Alternatively, you may get an error saying that you have recursive (or nested) includes.
A: You may have included the same header more than once in a file. Most likely, you have included one header file in another header file, and included both of them in a CPP file.
// this is myheader.h
class A
{
...
};
// this is mynewheader.h
#include "myheader.h" // notice I've included the above file
class B
{
};
// this is myCPP.cpp file
#include "myheader.h" // I've included myheader.h
// I've included a file that includes
// myheader.h, so the compiler thinks it should be included
// twice!
#include "mynewheader.h"
To fix this problem, you need to add "code guards". You can use some compiler commands called compiler directives to make sure every include file is "included" only once - thus preventing your code from being included multiple times. You should do this in every .h file.
// during compilation, this will ask the compiler
// if MYFILE_H is not defined defined
// this is like an if statement for the compiler
#ifndef MYFILE_H
// if we get here, it means it is not defined, so define it
// you don't need to give it a value
#define MYFILE_H
...
// if it was already defined, then the #ifndef will jump
// the compiler over the code to this line, thus
// not including any of the data!
#endif