Header 1 includes Header 2 Which Includes Header 1, How to solve?
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.
But the best way (well I think it is). Is to try and prevent these kind of loops.
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.
Put the bits that both Header1 and Header2 need, in Header3, and make Headers 1 and 2 include 3.
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,
I believe header files should be this way:
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.
#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.
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 ).
Ok, just to clarify here, you have something like this:
How does class1 need class2?
class1 - does... something.class2 - has the function that needs a class1::somefunction pointer
How does class1 need class2?
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.
You could also do:
#pragma once
instead of:
#ifndef HEADER
#define HEADER
// header file contents
#endif
#pragma once
instead of:
#ifndef HEADER
#define HEADER
// header file contents
#endif
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement