Search code examples
c++header

How to make one header to not include other headers?


So, if i have 3 headers like this

headers.h

#pragma once

#include <string>

#define FRAMEWORK_API extern "C" __declspec(dllimport)

class Sprite;

FRAMEWORK_API Sprite* createSprite(const char* path);

Event.h

#pragma once

#include "headers.h"

class Event
{
public:
    int spriteInit(std::string path = ".\\data\\Player\\TankPlayer*.png");
};

Event.cpp

int Event::spriteInit(std::string path)
{
    Sprite* newSpirte = createSprite(path);
}

Manager.h - Not deriving from Event, but includes

#pragma once

#include "Event.h"

class Manager
{
        /// Send event to all interested Objects.
        /// Return count of number of events sent.
        int onEvent(const Event *ptrEvent) const;
};

So, the question is, how to make Manager.h, not to see #include "headers.h", from Event.h?

I don't want Manager.h to see string and methods of the FRAMEWORK_API

UPDATE 1: I have changed names of Classes to make sense, why do i want to do this

UPDATE 2: I making it, because I can't #define FRAMEWORK_API extern "C" __declspec(dllimport) twice in the code


Solution

  • So, the question is, how to make ClassB.h, not to see #include "headers.h", from ClassA.h?

    By not including headers.h into ClassA.h. Or by not including ClassA.h into ClassB.h.

    In other words, you must give up on one of the premises, or your desire goal. They are in contradiction.

    If ClassA.h depends on declarations in headers.h1, and ClassB.h depends on declarations in ClassA.h2, then ClassB.h transitively depends on declarations in headers.h. If one of the assumptions 1 or 2 do not hold, then simply remove the unused include. If they hold, then you cannot avoid including definitions that you depend on. One thing that you may try is to get rid of one of the dependencies.


    Regarding the edited question

    #include "Event.h"
    
    class Manager
    {
            /// Send event to all interested Objects.
            /// Return count of number of events sent.
            int onEvent(const Event *ptrEvent) const;
    };
    

    The class Manager does not depend on the definition of the class Event. Therefore it doesn't need to include its definition. Manager only depends on the declaration of Event. Define a separate header that only has that definition.

    Furthermore, your Event.h does not depend on headers.h. The problem is solved by simply removing the unused include.

    // EventFwd.hpp
    class Event;
    
    
    // Event.hpp
    #pragma once
    #include "EventFwd.hpp"
    // do not include "headers.h"
    class Event
    {
    };
    
    
    // Manager.hpp
    #pragma once
    #include "EventFwd.hpp"
    // do not include "Event.hpp"
    class Manager
    {
        int onEvent(const Event *ptrEvent) const;
    };