c++dependenciescircular-dependencycyclic

C++ circular dependency with header guards and forward declarations


I have a simple Vec3 classand a simple xMath class.

The xMath class is supposed to change the Vec3. There are just 2 files Vec3.hpp and xMath.hpp (and I am not allowed to create other files).

Using Visual Studio 2019 Community Edition.

Getting errors:

Using the forward declarations, still getting errors:

Here are the files.

//Vec3.hpp
#ifndef VEC3_H
#define VEC3_H

#include "xMath.hpp"

namespace ns
{
    //class xMath; //forward declaration does not work either..

    struct Vec3
    {
    public:

        float x;

        //constructor
        Vec3(float x) { this.x = x; }

        static float Change(Vec3* v)
        {
            v->x = xMath::Change(v);

            return t;
        }

    };
}

#endif
//xMath.hpp
#ifndef XMATH_H
#define XMATH_H

#include "Vec3.hpp"

namespace ns
{
    //class Vec3; //forward declaration does not work either..

    static class xMath
    {
    public:

        static float Change (Vec3* v)
        {
            return v->x;
        }
    };
}

#endif

Solution

  • Those requirements are very strange. Normally we'd put the implementation in its own file that includes both headers.

    We can do something similar within the headers, though:

    #ifndef XMATH_H
    #define XMATH_H
    
    // First the declarations:
    
    namespace ns
    {
        class Vec3;
    
        class xMath
        {
        public:
            static float Change (Vec3* v);
        };
    }
    
    
    // Now the implementation (which would normally be in xMath.cpp):
    
    #include "Vec3.hpp"
    
    float ns::xMath::Change (Vec3* v)
    {
        return v->x;
    }
    
    #endif