This topic is 4876 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
{
...
};

#include "myheader.h"  // notice I've included the above file

class B
{
};

// this is myCPP.cpp file

// I've included a file  that includes
// myheader.h, so the compiler thinks it should be included
// twice!


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


##### Share on other sites
hold on did you just answer your own question in the same post? kinda pointless to post it if you ask me

##### Share on other sites
Quote:
 Original post by raptorstrikehold on did you just answer your own question in the same post? kinda pointless to post it if you ask me

Good thing noone did.

I'm sure some newbie will find this post useful. Not everyone knows to use #ifndef to keep from including header files more than once.

##### Share on other sites
...

...

... it was an attempt at wit. Leading by not-immediately-obvious example, you see.

Oh never mind.

##### Share on other sites
Quote:
 Posted by ontheheapI'm sure some newbie will find this post useful. Not everyone knows to use #ifndef to keep from including header files more than once.

Thats the long & short of it. I see that question come up at least once a week, so instead of retyping all that I decided to just make a 1 post about it. I forgot about Kylotan's guide - oops.