我在使用的每个头文件中都包含头文件时遇到问题

#pragma once

文件结构:
Main.cpp
- includes
  Main.h
  class definition

Main.h
- includes
  "class.h"
  "random_header.h"
  others ( windows , fstream )
  class declaration

Class.h
- includes
  "Main.h"
  class cApplication{ };

Other headers ( class, random_header ) include Main.h

类声明时Main.h中的错误:
error C2146: syntax error : missing ';' before identifier 'App' ( App is class name )
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

如果有任何帮助/提示,​​我将不胜感激。

Main.h代码
#pragma once

#pragma comment (lib, "d3d9.lib")
#pragma comment (lib, "d3dx9.lib")

#include <Windows.h>
#include <d3d9.h>
#include <d3dx9.h>

#include <fstream>

using namespace std;

#include "D3Ddefs.h"
#include "cApplication.h"

extern cApplication App; //error

LRESULT CALLBACK WindowProcedure(HWND,UINT,WPARAM,LPARAM);

好的,正如您所要求的,还有更多代码,以我的观点发布整个事情是没有意义的(如果不是,请告诉我),因此我将在此添加重要的内容。

Main.cpp
#include "Main.h"

cApplication App;

int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPreviousInstance,LPSTR lpcmdline,int nCmdShow)
{ ... }

D3Ddefs.h(完整)
#pragma once

#include "Main.h"

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE)

struct D3DVERTEX
{
float fX,
      fY,
      fZ;
DWORD dwColor;
};

cApplication.h
#pragma once

#include "Main.h"

class cApplication
{
private:
...
};

cApplication.cpp
#include "cApplication.h"


cApplication::cApplication(void)
{ ...
}

最佳答案

您所遇到的是一个循环包含问题。手动将每个#include替换为它们包含的内容的文件,并按其出现的顺序替换它们,而忽略先前包含的任何文件,您将在cApplication.cpp中看到“extern cApplication App;”。发生在cApplication的声明之上。

至于如何解决呢?在不知道cApplication.h为什么需要Main.h的情况下实际上无法告诉您。如果可以将依赖项分离出来,那么应该没问题。您是否正在尝试将cApplication设置为某种singleton,包括Main.h,以便可以访问该“App”变量?

10-04 11:48