c++ - 如何确保#include 不会递归添加(仅添加唯一文件一次)
问题描述
我有这个文件main.h
和这个文件events.h
,该文件events.h
需要包含main.h
,因为我的类的单例Events
需要我的类的单例Main
才能声明Main
为friend
类,因此它可以访问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
解决方案
这是一个链接器和头文件的问题,你只需要#pragma once
在每个头文件的顶部添加,编译器只会将每个头文件的内容添加一次,但是你必须确保你只是在你的头文件中声明方法并且将这些方法的内容写入其他.cpp
文件以防止链接错误。
推荐阅读
- ios - SwiftUI:在 iPad 的分屏中多次推送视图
- javascript - 对象属性复制错误 - 重复值 - 无法解释
- amazon-dynamodb - 具有 3 个或更多字段的 DynamoDB 过滤
- html - 如何在 CSS 网格中使用 @media 隐藏 div
- android - 使用 Firebase Auth 和 ChangeNotifierProvider 进行 Flutter 路由
- javascript - 使用 Express 构建第一个平均堆栈应用程序时遇到问题 - Nodemon
- docker - 同一网络中的 Docker 容器不通信
- fortran - 使用 Fortran 和 mpi 并行读/写 NetCDF 文件
- python - 当与 one-hot 编码向量一起使用时,如何解释 Keras 中嵌入层的输出形状?
- php - 使用 response() 在 Laravel 中获取错误