Jump to content

C++ Header Files


Recommended Posts

I'm writing a program in C++ which is spread across several different files. I've got a header file called "DataStructures.h" which strangely enough defines the layout of a couple of structs I use for storing data. Now these data structures are used thoughout my code, so are #included in all my other files. So the layout of my code looks something like this:

 

The main program

main.cpp (#includes DataStructures.h, class1.h and class2.h)

 

Several files that have classes, all of which use my data structures

class1.cpp/.h (#includes DataStructures.h)

class2.cpp/.h (#includes DataStructures.h)

 

The problem is my compiler then complains that my 2 data structures are declared multiple times within main.cpp which is true. As DataStructures.h is included within both of the class header files it gets it 3 times over. I've sort of got around this by daisy chaining the include statements but this is annoying. Is there some sort of command that says don't include if already included?

Link to comment
Share on other sites

You can use the preprocessor to do this, I think. In your *.h files, do something like this:

 

#ifndef DATASTRUCTURES_H

#define DATASTRUCTURES_H

 

<<the whole file goes here>>

 

#endif

 

You would, of course use a different variable for each file. That way, the preprocessor will see that DATASTRUCTURES_H is already defined already (included) and skip it.

Link to comment
Share on other sites

What Steve said, plus, you don't need the include in the main file if it's included in another file that is included... if you got that, yay, if not, don't worry about it and just do what Steve said. :)

Link to comment
Share on other sites

C++ has inheritance. that's the issue you're running into here. If it's included in the main file, any file included in that file inherits the include. What Steve said is a good way of working around it, but at the same time having that included several times is useless (and wastes a small small small amount of time checking if it's already defined).

Link to comment
Share on other sites

So if I include a header in main.cpp, I don't need to include it in sprite.cpp even if sprite.cpp needs access to the stuff in the header file?

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...