2

I have Environment.h file:

#include <windows.h>
#include "interfaces.h"

#ifndef ENVIRONMENT_H
#define ENVIRONMENT_H

class Environment {};
#endif

and i have Interfaces.h file:

#ifndef INTERFACES_H
#define INTERFACES_H

class IMoving {
    public: 
        virtual void Move() = 0;          
};

#endif

in interface IMoving i would like to get an Environment class, to know how to move

class IMoving {
    public: 
        virtual void Move(Environment*) = 0;          
};

if i want to do this i need to include environment.h

#include "Environment.h"

and here i'm getting an error, becouse Environment.h - includes Interfaces.h and Interfaces.h - includes Environtment.h. So how to make it work ?

Sorry for spelling mistakes

Mantas
  • 3,025
  • 1
  • 14
  • 9
  • You are asking "So how to make it work?". Could you please, be more specific? Background: Is is working if you can include Environtment.h in Interfaces.h and vice versa? Is this what you want to achieve? I just want to make sure whether I can provide a better answer. – Jörg Brüggmann Mar 11 '22 at 19:58

2 Answers2

4

It looks like you misspelled the class name a few times (Environtment,Envrirontment). Could that be the origin of your issue?

Otherwise I typically use the Forwarded Declaration

mox
  • 6,084
  • 2
  • 23
  • 35
4

For circular dependencies one can use Forward declaration(s)

In Interfaces.h just above interface definition, forward declare Environment as follows:

class Environment;

Then when you implement IMoving in a class, you will include Environment.h in its implementation (cpp) file.

You can read more about Forward declaration here.

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
  • 1
    @OzairKafay: This does not answer the question because the question seems to be about circular dependecies in terms of file inclusion by the C++ preprocessor - which the title already suggests. – Jörg Brüggmann Feb 23 '22 at 23:01
  • @JörgBrüggmann I did not really get your objection to my answer! One thing is that this is a 9 year old question, and the op accepted it at that time. Also, the only other answer is also suggesting forward declaration. However, I reviewing it again still makes me to say that he should forward declare Environment in the Interface.h and `include` Environment.h in cpp. – Ozair Kafray Mar 03 '22 at 11:45
  • 1
    @OzairKafay: May be your answer fits to the questioners intended purpose - but then the question should be edited. When answers fit to questions after 9 Years - then they are still helpful. The misconception in the question is "cyclic include" in conjunction with constructions like #ifndef XYZ #define XYZ. From my experience, this will never work. The title refers to include and not to declaration. – Jörg Brüggmann Mar 11 '22 at 20:13
  • Thanks for explaining @JörgBrüggmann. Would this be a better title: "How to declare classes to avoid circular dependencies?"? – Ozair Kafray Mar 16 '22 at 12:00