我的印象是标题守卫解决了重新定义的问题.我收到链接器错误,说明.obj文件中有重新定义.这是我所包含的标题,问题在于重新定义所有全局声明.
#ifndef DIRECT3D_H
#define DIRECT3D_H
// global declarations
ID3D10Device* device;
ID3D10Buffer* pBuffer;
ID3D10Buffer* iBuffer; // the pointer to the index buffer
ID3D10RenderTargetView* rtv; // the pointer to the render target view
ID3D10DepthStencilView* dsv; // the pointer to the depth stencil view
IDXGISwapChain* swapchain; // the pointer to the swap chain class
ID3D10Effect* pEffect;
ID3D10EffectTechnique* pTechnique;
ID3D10EffectPass* pPass;
ID3D10InputLayout* pVertexLayout;
ID3D10EffectMatrixVariable* pTransform; // the pointer to the effect variable interface
D3D10_PASS_DESC PassDesc;
// function prototypes
void initD3D(HWND hWnd);
void render_frame();
void init_pipeline();
void cleanD3D();
void Init();
#endif
Run Code Online (Sandbox Code Playgroud)
说这个标题叫做3DClass.h.它包含在3DClass.cpp中.它也包含在另一个文件中 - 一个主要的游戏循环.现在,我意识到当有多个翻译单元时头文件可能存在问题,但我不太明白为什么这不起作用,我只将头包含在一个文件中,也包含在相应的源文件中.这不应该没事吗?
标题保护解决了包括相同标题两次或隐藏递归包含的问题,而不是双重定义.
如果您在不同的翻译单元中包含相同的标题,标题保护将无济于事.
解决方案是永远不要在头文件中声明变量.如果需要共享变量,请extern在标题中使用关键字,并在其中一个翻译单元中声明实际变量.