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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...