开发者

Header guard / translation unit problem

I was under the impression that header guards solve the problem of redefinition. I'm getting linker errors that say there are redefinitions in the .obj files. This is the header I'm including, the problems are with the redefinition of all the global declarations.

#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;
ID3D10EffectMat开发者_开发百科rixVariable* 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

say this header is called 3DClass.h. It is included in 3DClass.cpp. It is also included in another file - a main game loop. Now, I realise there can be problems with header files when there are multiple translation units, but I don't quite understand why this wouldn't be working, i'm only including the header in one file and also in the corresponding source file. shouldn't this be fine?


Header guards solve the problem of including the same header twice or hidden recursion of includes, not double definition.

If you include the same header in different translation units, header guards won't help.

The solution is to never declare variables in header files. If you need to share variables, use the extern keyword in the header, and declare the actual variables in one of the translation units.


Header guards only prevent the guarded portion of the header file from being included twice. The result is passed to the compiler, so the compiler does not know anything of the header guards.

Consequently it will emit these symbols for every translation unit that includes the header (since it can not know that there was somewhere another unrelated translation unit compiled).

Also the linker can not know that you didn't wanted this to happen.

To solve the problem, declare the variables extern in the header, and define them in one single translation unit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜