Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我连头球护卫都会出现链接错误?_C++ - Fatal编程技术网

C++ 为什么我连头球护卫都会出现链接错误?

C++ 为什么我连头球护卫都会出现链接错误?,c++,C++,可能重复: 全球 #ifndef Global_h #define Global_h #include <iostream> unsigned char exitStatus; #endif 根 #ifndef Root_h #define Root_h // declarations OutputHandler *output; #endif Root.cpp #include "Root.h" // gets instance of OutputHandler

可能重复:

全球

#ifndef Global_h
#define Global_h

#include <iostream>

unsigned char exitStatus;

#endif

#ifndef Root_h
#define Root_h

// declarations

OutputHandler *output;

#endif
Root.cpp

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

关于exitStatus静态bool instanceExists,以及静态类输出已由OutputHandler.obj中的Root.obj定义,我遇到了错误。我假设问题在于将头文件OutputHandler.h同时包含在Root.hOutputHandler.cpp中。任何人都知道如何修复这个文件,或者如何更好地组织头文件?

< p>声明>代码>外部引用char ExtStase<代码> > <代码> Global .h <代码>,并将其定义在一个实现文件中。

,因为包含保护只在翻译单元级别工作(对于这个简单的情况,您可以考虑单个C文件作为翻译单元)。 这意味着一个C文件,如果它包含头文件两次,由于包含保护,将不会第二次处理它

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

然后,当您将它们链接在一起时,您将获得副本

解决这个问题的最简单方法是永远不要在标题中定义内容,而只声明它们

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

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

#include <iostream>

usigned char exitStatus;

#endif
在所有想要使用它的C文件中,放:

$include "xyzzy.h"
并且,在其中一个C文件中,还放入:

int xyzzy;        // define it here, once.

您可以将声明看作是一个简单的“我声明它存在于某个地方,而不是这里”,而定义是“我在此时此地创建它”。

问题在于链接阶段;在标题中包含卫士对您没有帮助

在C语言中,有声明和定义的独立概念。声明是放在标题中的内容;它们仅仅说明存在一个特定的变量。变量的定义是实际为其分配存储的位置

例如,在您的
Global.h
中,您有:

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

#include <iostream>

usigned char exitStatus;

#endif
并且仅在一个源文件中,使用以下内容定义它:

对于
Root.h
中的
output
,以及您应该在头文件中声明变量的任何其他位置,情况类似


另请参见:

问题的答案详细解释了原因。简而言之,您不应该在头文件中定义对象,然后在多个TU中包含该头文件。它违反了ODR。
char exitStatus;