Sign in to follow this  
dave

Header 1 includes Header 2 Which Includes Header 1, How to solve?

Recommended Posts

mldaalder    193
So Header1 includes Header2 and then Header2 includes Header1 (just getting the facts straight).

Well, both of the headers start with something like this:
#ifndef HEADER#_H
#define HEADER#_H
// Code
#endif


Well, include similar tags around the #include statements.

//Header1:
#ifndef HEADER1_H
#define HEADER1_H

#ifndef HEADER2_H
#include"Header2.h"
#endif

// Rest of code
#endif

//Header2:
#ifndef HEADER2_H
#define HEADER2_H

#ifndef HEADER1_H
#include"Header1.h"
#endif

// Rest of code
#endif



But the best way (well I think it is). Is to try and prevent these kind of loops.

Share this post


Link to post
Share on other sites
dave    2187
The problem is that i want to pass a pointer to a function into the other class, but since the pointer is of type class1, class2 needs the class1 header so it can recieve it,

Share this post


Link to post
Share on other sites
liquidAir    314
I believe header files should be this way:


#ifndef HEADER
#define HEADER

// header file contents

#endif


Or maybe you have defined variables in the header files, and it complains about the objects already being defined in so-so file. It is more advisable to define your variables in the source files, not header files.

Share this post


Link to post
Share on other sites
python_regious    929
Ok, then create a forward declaration of class1, then in the source file include the header with the definition. ( I think I got declare/define the right way round, I do tend to mix them up ).

Share this post


Link to post
Share on other sites
Charles B    863
It's called a cyclic dependency. Avoid it as much as possible, not only for headers, but also classes, modules etc... The less you have the better your code is architectured. You can use call backs very often to keep your code modular.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Quote:
Original post by Mussi
You could also do:

#pragma once

instead of:

#ifndef HEADER
#define HEADER

// header file contents

#endif


Yes, you could use #pragma once instead of include guards if you want to write invalid C++ code.

Share this post


Link to post
Share on other sites
silvermace    634
Quote:
Original post by Mussi
You could also do:

#pragma once

instead of:

#ifndef HEADER
#define HEADER

// header file contents

#endif


pragma once does not guarantee that the file will not get included again, it simply guarantees that the preprocessor will not read the file again.

Share this post


Link to post
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

Sign in to follow this