标题保护/翻译单元问题 [英] Header guard / translation unit problem

查看:130
本文介绍了标题保护/翻译单元问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的印象是,标题卫士解决了重新定义的问题。我收到链接器错误,说有重新定义.obj文件。这是我包含的标题,问题是重新定义所有的全局声明。

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;
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

说这个标题叫3DClass.h。它包含在3DClass.cpp中。它也包括在另一个文件 - 主游戏循环。现在,我意识到,当有多个翻译单元时,头文件可能会有问题,但我不太明白为什么这不会工作,我只包括头在一个文件,也在相应的源文件。不应该这样罚款吗?

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?

推荐答案

标题防护解决了包含相同标头两次或隐藏递归的include而不是双精度的问题。

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.

解决方案是从不在头文件中声明变量。如果您需要共享变量,请在标题中使用 extern 关键字,并在一个翻译单元中声明实际变量。

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.

这篇关于标题保护/翻译单元问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆