首页 > 解决方案 > 如何确保#include 不会递归添加(仅添加唯一文件一次)

问题描述

我有这个文件main.h和这个文件events.h,该文件events.h需要包含main.h,因为我的类的单例Events需要我的类的单例Main才能声明Mainfriend类,因此它可以访问Events私有成员/方法。

相反,Main也需要 includeEvents来调用它的方法,但是#include "events.h"在 main 中做,然后#include "main.h"在事件中只会递归地在每个方法中粘贴头文件代码。

我怎样才能避免这种情况,以便他们每个人只在每个文件中粘贴一次代码?

主文件

#ifndef MAIN_H
#define MAIN_H

#include "events.h"

class Main
{
public:
    Main(const Main&) = delete;
    Main(Main&&) = delete;
    Main& operator=(const Main&) = delete;
    Main& operator=(Main&&) = delete;


    static void Mainloop();




private:
    Main()
    {
        std::cout << "Main constructor called\n";
        mainloopInstanceBlocker = 'C';
    }

    static Main& Get_Instance()
    {
        static Main instance;
        return instance;
    }


    static void Init();
    static void Free();



    SDL_Window* window = nullptr;
    SDL_Renderer* renderer = nullptr;

    bool running = false;
    char mainloopInstanceBlocker = 'I';



};








#endif // MAIN_H

事件.h

#ifndef EVENTS_H
#define EVENTS_H


#include <iostream>
#include <SDL2/SDL.h>
#include <string>


#include "main.h"


class Events
{
public:
    Events(const Events&) = delete;
    Events(Events&&) = delete;
    Events& operator=(const Events&) = delete;
    Events& operator=(Events&&) = delete;



    static const std::string& User_Text_Input();




private:
    Events()
    {
        std::cout << "Events constructor called\n";
    }

    static Events& Get_Instance()
    {
        static Events instance;
        return instance;
    }


    friend class Main;

    ///For event handling
    static void Event_Loop()
    {
        Get_Instance();

        if (Get_Instance().eventLoopCounter == 0)
        {

            Get_Instance().eventLoopCounter += 1;

            while (SDL_PollEvent(&Get_Instance().event))
            {
                if (Get_Instance().event.type == SDL_QUIT)
                {
                    Get_Instance().m_quit = true;
                    break;
                }
                else if (Get_Instance().event.type == SDL_TEXTINPUT)
                {
                    Get_Instance().m_User_Text_Input = Get_Instance().event.text.text;
                }


            }

        }
    }

    ///For event handling
    static void Reset_Events()
    {
        Get_Instance().eventLoopCounter = 0;

        Get_Instance().m_quit = false;
        Get_Instance().m_User_Text_Input = "";
    }

    ///For quitting, used main only
    static bool Quit_Application(){
        return Get_Instance().m_quit;
    }



    ///For Event_Loop()
    int eventLoopCounter = 0;
    SDL_Event event;




    bool m_quit = false;

    std::string m_User_Text_Input = "";



};



#endif // EVENTS_H

标签: c++headerinclude-guardscyclic-dependency

解决方案


这是一个链接器和头文件的问题,你只需要#pragma once在每个头文件的顶部添加,编译器只会将每个头文件的内容添加一次,但是你必须确保你只是在你的头文件中声明方法并且将这些方法的内容写入其他.cpp文件以防止链接错误。


推荐阅读