为什么即使使用标头防护也出现链接错误? [英] Why am I getting linking errors even with header guards?

查看:63
本文介绍了为什么即使使用标头防护也出现链接错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么这不能阻止多个函数的声明?

Global.h

  #ifndef Global_h#define Global_h#include< iostream>未签名的char exitStatus;#万一 

OutputHandler.h

  #ifndef OutputHandler_h#定义OutputHandler_h#include"Global.h"类OutputHandler {私人的:静态布尔实例//更多代码#万一 

Root.h

  #ifndef Root_h#define Root_h//声明OutputHandler *输出;#万一 

Root.cpp

  #include"Root.h"//获取OutputHandler的实例//更多代码 

我收到有关 exitStatus 静态布尔实例存在静态类输出的错误,这些错误已经由 Root.obj 中的 OutputHandler.obj .我认为问题在于在 Root.h OutputHandler.cpp 中都包含了头文件 OutputHandler.h .有谁知道如何解决此问题或如何更好地组织头文件?

解决方案

因为include防护仅在翻译单元级别起作用(对于这种简单情况,您可以将单个C文件视为翻译单元).

这意味着如果单个C文件包含两次头文件,由于包含保护,第二次将不对其进行处理.

但是,如果包含两个不同 C文件的标头,则每个 都将获得该标头中定义的变量的副本.

然后,将它们链接在一起时,就会得到重复项.

解决此问题的最简单方法是,永远不要在标头中定义任何东西,只声明它们.

因此,在标题(例如 xyzzy.h )中,您具有:

  extern int xyzzy;//声明但不定义. 

,并在所有要使用的C文件中,放入:

  $ include"xyzzy.h" 

,并在这些C文件的一个中,放置:

  int xyzzy;//在此定义一次. 

您可以将声明视为一个简单的我声明它存在于某个地方,但不存在于此处",而定义是我正在此处创建此地".

Possible Duplicate:
Why does this not prevent multiple function declarations?

Global.h

#ifndef Global_h
#define Global_h

#include <iostream>

unsigned char exitStatus;

#endif

OutputHandler.h

#ifndef OutputHandler_h
#define OutputHandler_h

#include "Global.h"

class OutputHandler {
private:
    static bool instanceExists;
// more code  

#endif

Root.h

#ifndef Root_h
#define Root_h

// declarations

OutputHandler *output;

#endif

Root.cpp

#include "Root.h"
// gets instance of OutputHandler
// more code

I am getting errors regarding exitStatus, static bool instanceExists, and static class output being already defined by Root.obj in OutputHandler.obj. I assume the issue is with including the header file OutputHandler.h in both Root.h and OutputHandler.cpp. Anyone know how to fix this or how to better organize header files?

解决方案

Because include guards only work at the translation unit level (you can, for this simple case, consider a single C file to be a translation unit).

That means a single C file, if it includes the header file twice, will not process it the second time due to the include guards.

However, if you include the header from two different C files, each of them will get a copy of the variables defined in that header.

Then, when you link them together, you get the duplicates.

The easiest way to get around this problem is to never define things in headers, only declare them.

So, in the header (eg, xyzzy.h), you have:

extern int xyzzy;  // declare but don't define.

and in all the C files that want to use that, put:

$include "xyzzy.h"

and, in one of those C files, also put:

int xyzzy;        // define it here, once.

You can think of declaration as a simple "I declare that this exists somewhere, just not here", while definition is "I an creating this here and now".

这篇关于为什么即使使用标头防护也出现链接错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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